(function( window, undefined ) {
var document = window.document,
	location = window.location;

//expose any public members in this
//defined after functions are implemented
var deconf = window.DEConfig,
    deEvents = {
      'pageChange':'pageChangeEvent',
      'renderPage': 'renderPageEvent',
      'levelReady': 'levelReadyEvent',
      'dragFinish': 'dragFinishEvent',
      'clipFinish': 'clipFinishEvent',
      'pageDataLoaded': 'pageDataLoadedEvent',
      'autoScroll':'autoScrollEvent',
      'showAuthBox': 'showAuthBoxEvent',
      'showLoginBox': 'showLoginBoxEvent',
      'pluginsLoaded': 'pluginsLoadedEvent',
      'loginChecked': 'loginCheckedEvent'
    },
    pageData = {},
    sectionData = {},
    currentLevel,
    clickPos,
    clickPosRatio,
    lastScreenPos,
    lastScrollPos,
    pageOffset,
    navBarOffset,
    navBarFixed,
    winHeight,
    winWidth,
    isDragging,
    isClipping,
    $clipRect,
    overlayShadow,
    $pageContainer,
    allDataLoaded,
    mousePos,
    de = {
      'prepareForClipping':'',
      'openSubscribe':'',
      'cancelClipping':'',
      'allPageDataLoaded':false,
      'pageData':'',
      'sectionData':'',
      'allSectionDataLoaded':false,
      'zooms':'3',
      'isautoScroll':false,
      'forceCloseSidebar': false,
      'plugins':{},
      'emails':[]
    },
    thumbContainerPos,
    pageWidth,
    pageHeight,
    screenWidth,
    screenHeight,
    screenMouseX,
    screenMouseY,
    pageTop,
    pageLeft,
    avgScrollLeft,
    avgScrollTop,
    avgScrollRight,
    avgScrollBottom,
    firstPage,
    clickPage,
    footerStatus = true,
    footerResizing = false,
    userdata,
    subscriberdata = false,
    resetFooter = false;


function getTemplate(id){
  return
}

if(deconf.DEBUG){
  var origTrigger = $.fn.trigger;
  $.fn.trigger = function(){
    console.log('triggered '+ arguments[0]);
    origTrigger.apply(this, arguments);
  }
}

function isBrowserUnsupported()
{
  var isIe55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
  var isIe6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
  var isIe7 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 7.0") != -1);
  return isIe55 || isIe6 || isIe7;
}

function generateLink()
{
  arguments.join = [].join;
  //join base url with given arguments
  return deconf.baseUrl + arguments.join('/') + deconf.authToken;
}

function getPageData(){
  return pageData;
}

function getLevel(num,zoom){
    var lvl;
    if(! pageData.hasOwnProperty(num) ){
    	return undefined;
    }
    zoom = Number(zoom);

    switch(zoom)
    {
        case 1:
            if ((de.mode=='page') && (screen_width >= 600)){
                lvl = pageData[num].levels.leveldefault;
            }else{
                lvl = pageData[num].levels.level0;
            }
            break;
        case 2:
            lvl = pageData[num].levels.level1;
            break;
        case 3:
            lvl = pageData[num].levels.level2;
            break;
    }
    return lvl;
}

function intersects(rect1, rect2){
  //take projection on x and y
  //if both overlap, intersects = true
  //return true;
  var xInt = (rect1.x < rect2.x) ? rect2.x < (rect1.x + rect1.w) :
    rect1.x < (rect2.x+rect2.w);

  var yInt = (rect1.y < rect2.y) ? rect2.y < (rect1.y + rect1.h) :
    rect1.y < (rect2.y+rect2.h);
  return xInt && yInt;
}

function showVisibleChunks()
{
  //run a for loop
  //check if the chunk is visible
  //clear and put image in it.

  var scrollTop = $(window).scrollTop();
  var scrollLeft = $(window).scrollLeft();
  //find visible area of page
  var ya,xa,y = 0, x = 0, width = 0, height = 0, wH, wW;
  ya = scrollTop - pageOffset.top;
  y = (ya > 0) ? ya : 0;
  wH = winHeight - ((ya < 0) ? -ya : 0);

  xa = scrollLeft - pageOffset.left;
  x = (xa > 0) ? xa : 0;
  wW = winWidth - ((xa < 0) ? -xa : 0);
  height = currentLevel.height - y;
  height = (height < wH) ? height : wH;
  if (isSingleView()) {
      width = currentLevel.width - x;
  }else{
    width = currentLevel.width*2 - x;
  }
  width = (width < wW) ? width : wW;
  var visibleRect = {'x':x,'y':y,'w':width,'h':height};

  //
//  $('#overlay').remove();
//  $overlay = $('<div id="overlay" style="-moz-box-shadow:0 0 5px #000;position:absolute;"></div>');
//  $overlay.css('top', visibleRect.y+'px').css('left', visibleRect.x+'px');
//  $overlay.width(visibleRect.w).height(visibleRect.h);
//  $('#de-chunks-container').append($overlay);
  //
  var chunk, $chunkdiv;
  var level = getLevel(de.page,de.zoom);

  if (!level){return;}
  for (var idx in level.chunks){
    if(! level.chunks.hasOwnProperty(idx) ) continue;

    //find the div which is not loaded, get its rect
    //detect its intersection with visible rect
    //put image in it and mark it as loaded
    chunk = level.chunks[idx];
    $chunkdiv = $("#left-chunk-"+idx);
    if($chunkdiv.attr('loaded') == 'true') continue;

    chunkRect = {'x':Number($chunkdiv.css('left').replace('px','')),
      'y':Number($chunkdiv.css('top').replace('px','')),
      'w':$chunkdiv.width(),
      'h':$chunkdiv.height()};
    if(! intersects(chunkRect, visibleRect)) continue;

    $chunkdiv.attr('loaded', 'true');

    if (jQuery.browser.msie && isBrowserUnsupported() && chunk.url.indexOf('.png') != -1 ) {
      chunkdiv.style.width= chunk.width + 'px';
      chunkdiv.style.height= chunk.height + 'px';
      $chunkdiv.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader"+
       "(src=\'" + chunk.url + "\', sizingMethod='image')");
    }else{
      var cimg = new Image();
      cimg.alt = "";
      cimg.style.width = chunk.width + 'px';
      cimg.style.height = chunk.height + 'px';
      cimg.width = Number(chunk.width);
      cimg.height = Number(chunk.height);
      $chunkdiv.append(cimg);
      cimg.src = chunk.url;
    }
  }

  if (!isSingleView()){
      var chunk, $chunkdiv;
      var level_1 = getLevel(Number(de.page)+1, de.zoom);

      for (var idx in level_1.chunks){
        if(! level_1.chunks.hasOwnProperty(idx) ) continue;

        //find the div which is not loaded, get its rect
        //detect its intersection with visible rect
        //put image in it and mark it as loaded
        chunk = level_1.chunks[idx];
        $chunkdiv = $("#right-chunk-"+idx);
        if($chunkdiv.attr('loaded') == 'true') continue;

        chunkRect = {'x':Number($chunkdiv.css('left').replace('px','')),
          'y':Number($chunkdiv.css('top').replace('px','')),
          'w':$chunkdiv.width(),
          'h':$chunkdiv.height()};
        if(! intersects(chunkRect, visibleRect)) continue;

        $chunkdiv.attr('loaded', 'true');

        if (jQuery.browser.msie && isBrowserUnsupported() && chunk.url.indexOf('.png') != -1 ) {
          chunkdiv.style.width= chunk.width + 'px';
          chunkdiv.style.height= chunk.height + 'px';
          $chunkdiv.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader"+
           "(src=\'" + chunk.url + "\', sizingMethod='image')");
        }else{
          var cimg = new Image();
          cimg.alt = "";
          cimg.style.width = chunk.width + 'px';
          cimg.style.height = chunk.height + 'px';
          cimg.width = Number(chunk.width);
          cimg.height = Number(chunk.height);
          $chunkdiv.append(cimg);
          cimg.src = chunk.url;
        }
      }
  }
}

function autoloadChunks(){
    var chunk, $chunkdiv;
    var level = getLevel(de.page,de.zoom);

    for (var idx in level.chunks){
        if(! level.chunks.hasOwnProperty(idx) ) continue;

        //find the div which is not loaded, get its rect
        //detect its intersection with visible rect
        //put image in it and mark it as loaded
        chunk = level.chunks[idx];
        $chunkdiv = $("#left-chunk-"+idx);
        if($chunkdiv.attr('loaded') == 'true') continue;

        chunkRect = {'x':Number($chunkdiv.css('left').replace('px','')),
          'y':Number($chunkdiv.css('top').replace('px','')),
          'w':$chunkdiv.width(),
          'h':$chunkdiv.height()};

        $chunkdiv.attr('loaded', 'true');

        if (jQuery.browser.msie && isBrowserUnsupported() && chunk.url.indexOf('.png') != -1 ) {
          chunkdiv.style.width= chunk.width + 'px';
          chunkdiv.style.height= chunk.height + 'px';
          $chunkdiv.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader"+
           "(src=\'" + chunk.url + "\', sizingMethod='image')");
        }else{
          var cimg = new Image();
          cimg.alt = "";
          cimg.style.width = chunk.width + 'px';
          cimg.style.height = chunk.height + 'px';
          cimg.width = Number(chunk.width);
          cimg.height = Number(chunk.height);
          $chunkdiv.append(cimg);
          cimg.src = chunk.url;
        }
      }
    if (!isSingleView()){
        var level_1 = getLevel(Number(de.page)+1, de.zoom);

      for (var idx in level_1.chunks){
        if(! level_1.chunks.hasOwnProperty(idx) ) continue;

        //find the div which is not loaded, get its rect
        //detect its intersection with visible rect
        //put image in it and mark it as loaded
        chunk = level_1.chunks[idx];
        $chunkdiv = $("#right-chunk-"+idx);
        if($chunkdiv.attr('loaded') == 'true') continue;

        chunkRect = {'x':Number($chunkdiv.css('left').replace('px','')),
          'y':Number($chunkdiv.css('top').replace('px','')),
          'w':$chunkdiv.width(),
          'h':$chunkdiv.height()};
        if(! intersects(chunkRect, visibleRect)) continue;

        $chunkdiv.attr('loaded', 'true');

        if (jQuery.browser.msie && isBrowserUnsupported() && chunk.url.indexOf('.png') != -1 ) {
          chunkdiv.style.width= chunk.width + 'px';
          chunkdiv.style.height= chunk.height + 'px';
          $chunkdiv.css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader"+
           "(src=\'" + chunk.url + "\', sizingMethod='image')");
        }else{
          var cimg = new Image();
          cimg.alt = "";
          cimg.style.width = chunk.width + 'px';
          cimg.style.height = chunk.height + 'px';
          cimg.width = Number(chunk.width);
          cimg.height = Number(chunk.height);
          $chunkdiv.append(cimg);
          cimg.src = chunk.url;
        }
      }
    }
    
}

function renderPage(pgnum,side){

    var num_levels = 0;
    var regex = /^level\d.*$/;
    for(var idx in pageData[pgnum].levels){
      if( regex.test(idx) ){
          num_levels += 1;
      }
    }
    de.zoomLevels = num_levels;

    var level = getLevel(pgnum, de.zoom); //alert("level_width "+level.width);
    currentLevel = level;
    if (side=='left'){
        var $mainView = $("#de-chunks-container").empty();
        var bgThumbdiv = document.createElement("div");
        var bgThumbimg = new Image();
        bgThumbdiv.id = "left-bgThumbdiv";
        bgThumbdiv.style.width = bgThumbimg.style.width = level.width + 'px';
        bgThumbdiv.style.height = bgThumbimg.style.height = level.height + 'px';
        bgThumbdiv.style.position = "absolute";
        bgThumbdiv.style.left = "0px";
        bgThumbdiv.style.top = "0px";
        bgThumbimg.width = Number(level.width);
        bgThumbimg.height = Number(level.height);
        bgThumbdiv.appendChild(bgThumbimg);
        $mainView.append(bgThumbdiv);

        bgThumbimg.alt = "";
        bgThumbimg.onload = function(evt){
        $(window).trigger(deEvents.levelReady);
        };
        bgThumbimg.src = pageData[pgnum].levels.thumbs.chunks[0].url;

        var chunk, chunkdiv;
        for (var idx in level.chunks){
            if(! level.chunks.hasOwnProperty(idx) ) continue;

            chunk = level.chunks[idx];
            chunkdiv = document.createElement("div");
            chunkdiv.style.position="absolute";
            chunkdiv.style.top= chunk.ty + 'px';
            chunkdiv.style.left= chunk.tx + 'px';
            chunkdiv.style.width = chunk.width + 'px';
            chunkdiv.style.height = chunk.height + 'px';
            chunkdiv.id = "left-chunk-"+idx;

            $mainView.append(chunkdiv);
        }

        if (de.mode=='page' || de.page==1 || de.page==deconf.numPages){
            $(window).trigger(deEvents.renderPage);
        }
    }else if (side=='right'){
        var $mainView = $("#de-chunks-container");
        var bgThumbdiv = document.createElement("div");
        var bgThumbimg = new Image();
        bgThumbdiv.id = "right-bgThumbdiv";
        bgThumbdiv.style.width = level.width + 'px';
        bgThumbdiv.style.height = level.height + 'px';
        bgThumbdiv.style.position = "absolute";
        bgThumbdiv.style.left = level.width + "px";
        bgThumbdiv.style.top = "0px";
        bgThumbimg.width = level.width;
        bgThumbimg.height = level.height;

        bgThumbdiv.appendChild(bgThumbimg);
        $mainView.append(bgThumbdiv);

        bgThumbimg.alt = "";
        bgThumbimg.onload = function(evt){
        $(window).trigger(deEvents.levelReady);
        };
        bgThumbimg.src = pageData[pgnum].levels.thumbs.chunks[0].url;

        var chunk, chunkdiv;
        for (var idx in level.chunks){
            if(! level.chunks.hasOwnProperty(idx) ) continue;

            chunk = level.chunks[idx];
            chunkdiv = document.createElement("div");
            chunkdiv.style.position="absolute";
            chunkdiv.style.top= chunk.ty + 'px';
            chunkdiv.style.left= Number(level.width) + Number(chunk.tx) + 'px';
            chunkdiv.style.width = chunk.width + 'px';
            chunkdiv.style.height = chunk.height + 'px';
            chunkdiv.id = "right-chunk-"+idx;

            $mainView.append(chunkdiv);
        }
        $(window).trigger(deEvents.renderPage);
    }
}

function changePage(){
  switch (de.mode){
      case 'page' :loadSinglePage();break;
      case 'dual' :loadDualPage();break;
  }
}

function loadPage(pgnum1, pgnum2){

  if (pgnum2){
      if(pageData.hasOwnProperty(pgnum1) && pageData.hasOwnProperty(pgnum2)){
          renderPage(pgnum1,'left');
          renderPage(pgnum2,'right');
          return;
      }
  }else{
      if(pageData.hasOwnProperty(pgnum1)){
          renderPage(pgnum1,'left');
          return;
      }
  }

  $.getJSON( generateLink('pagemeta/get',deconf.volumeId, pgnum1 + "-" + ((pgnum2) ? pgnum2 : pgnum1)),
    function(response){
        pageData[pgnum1]=response[pgnum1];
        renderPage(pgnum1,'left');
        if (pgnum2){
            pageData[pgnum2] = response[pgnum2];
            renderPage(pgnum2,'right');
        }
    }
  );
}

function loadSinglePage(){
  loadPage(de.page, undefined);
}

function loadDualPage(){
  if (de.page == 1 || de.page == deconf.numPages){
     loadSinglePage();
  }else if (de.page % 2 ==0){
      loadPage(de.page,Number(de.page)+1);
  }else{
      de.page = de.page - 1;
      window.location.hash = DE.mode+'/'+de.page+'/'+de.zoom;
  }
}

function adjustInterface()
{
  var pWidth = $('#left-bgThumbdiv').width(),
      pHeight = $('#left-bgThumbdiv').height();
  $('.page-size').each(function(){
      if (isSingleView()){
          $(this).width(pWidth).height(pHeight);
          $('#de-page-wrapper').width(pWidth);
      }else{
          $(this).width(pWidth+$('#right-bgThumbdiv').width()).height(pHeight);
          $('#de-page-wrapper').width(pWidth+$('#right-bgThumbdiv').width());
      }
  });
  pageOffset = $('#de-chunks-container').offset();

  //$("#de-container").height($("#de-container").height()+$("#de-page-toolbox").height());

  if(de.zoom > 1){
    if(clickPosRatio){ 
        var maxScrollTop = Number(currentLevel.height) + pageOffset.top - winHeight;
        var maxScrollLeft = 0;
        if (isSingleView())
            maxScrollLeft = Number(currentLevel.width) + pageOffset.left - winWidth;
        else
            maxScrollLeft = Number(currentLevel.width*2) + pageOffset.left - winWidth;

        newx = clickPosRatio.x * maxScrollLeft,
        newy = clickPosRatio.y * maxScrollTop;

        $(window).scrollTop(newy);
        $(window).scrollLeft(newx);
    }else{
        $(window).scrollTop(0);
        $(window).scrollLeft(0);
    }
    if(Modernizr.touch) {
        $('body').css('overflow','visible');
        $('#de-navbar').css('width','510px');
    }
  } else {
      if(Modernizr.touch) {
          $('#de-navbar').css('width',screen_width);
          $('body').css('overflow','hidden');
          if($(window).scrollTop() > 90) {                                    
             setTimeout(function(){$('#de-navbar').css({'top':(($(window).scrollTop()))+'px','left':pageOffset.left+'px'})},50);
          } else {
              setTimeout(function(){$('#de-navbar').css({'top':navbar_top+'px','left':pageOffset.left+'px'})},50);
          } 
           
      }
  }
  $("#de-bottom-ad").css({'top':180+Number(currentLevel.height)+'px'});
  $(window).trigger('scroll');
  

}

function checkUrl(){
  var hashStr = window.location.hash.substr(1);
	if(! hashStr){
	  //location.hash = '#page/1/1';
	  hashStr = 'page/1/1';
	}
	//match legacy hashes
	if(hashStr.indexOf(':') > -1){
	  //old style
	  var hash = hashStr.split(':');
	  var keyval;
	  var retObj = {};
	  for(var idx in hash){
		  if(! hash.hasOwnProperty(idx)) continue;

		  keyval = hash[idx];
		  keyval = keyval.split('=');
		  retObj[ keyval[0] ] = keyval[1];
	  }
	  if(retObj.p){
	    location.hash = '#'+retObj.p+'/'+retObj.n+'/'+ ((retObj.z)?retObj.z : 1);
	  }else{
	    location.hash = '#'+hash[0]+'/'+hash[1]+'/'+hash[3];
	  }
	  return;
	}

	var hash = hashStr.split('/');
	de.mode = hash[0];
	de.page = hash[1];
	de.zoom = hash[2];
	//call the handler
	$(window).trigger(deEvents.pageChange);
}

function setCursor(){
  //set page cursor according to situation
  //if not zoomed in, show lens cursor
  //if isclipping, show crosshair
  //if is dragging
}

function loadClip(clipType){

  //take the coods of given clip if clip id not found
  //and send a request to api for clip
  //show a loader image till it returns
  var pageKey = pageData[de.page].key;

  var clipId = $('#clip-rect-btn').attr('data-clipid');

  if(clipId){
    loadOldClip(clipId, clipType);
  }else{
    createNewClip(pageKey, clipType);
  }
}

function createNewClip(pageKey,clipType){
    var $clip = $('#clip-rect');
        clipPos = $clip.position();

        if (!isSingleView() && clickPage%2==1){//making clip in dual mode's second page
            clipPos.left = clipPos.left - currentLevel.width;
            pageKey = pageData[clickPage].key;
        }
        x0 = clipPos.left / Number(currentLevel.width),
        y0 = clipPos.top / Number(currentLevel.height),
        x1 = (clipPos.left+$clip.width())/ Number(currentLevel.width),
        y1 = (clipPos.top+$clip.height())/ Number(currentLevel.height);

    x0 = (x0 > 0)? x0 : 0;
    y0 = (y0 > 0)? y0 : 0;
    x0 = (x0 < 1)? x0 : 1;
    y0 = (y0 < 1)? y0 : 1;

    x1 = (x1 > 0)? x1 : 0;
    y1 = (y1 > 0)? y1 : 0;
    x1 = (x1 < 1)? x1 : 1;
    y1 = (y1 < 1)? y1 : 1;

    $.getJSON(deconf.baseUrl+'clip/create/'+pageKey+'/'+x0+'/'+y0+'/'+x1+'/'+y1,
    function(response){
        renderClip(response, clipType);
        addClipEntryInPageData(pageKey,x0,y0,x1,y1,response.clipid);
        clearCache();
        showPreClipped();
        addUserClip(response);
    });
}

function clearCache(){
    $.get(deconf.baseUrl+'api/clearmetacache/'+deconf.volumeId,{},function(response){});
}

function addClipEntryInPageData(pageKey,x0,y0,x1,y1,clipid){
    for (var id in pageData){
        if (pageData.hasOwnProperty(id) && pageData[id].key == pageKey){
            pageData[id]['clips'].push({'x0':x0,'y0':y0,'x1':x1,'y1':y1,'id':clipid});
        }
    }
}

function loadOldClip(clipId,clipType){
    $.getJSON(deconf.baseUrl+'clip/get/'+clipId,
    function(response){
        renderClip(response, clipType);
    });
}

function renderClip(response, clipType){
    if (clipType=='share'){
        var loadScript = function(d, s, id, src) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement(s);js.id = id;
            js.src = src;
            fjs.parentNode.insertBefore(js, fjs);
          };

      var showClipSharingOptions = function(clip_link){
          $('#clip-short-link').val(clip_link);
          $('#clip-fb-comments').attr('data-href', clip_link);
          $('#clip-content .sharing-btns').append('<a href="https://twitter.com/share" '+
          'class="twitter-share-button" data-url="'+clip_link+'" data-count="vertical">Tweet</a>'+
          '<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>')
          .append('<div id="fb-root"></div><div class="fb-like" data-href="'+clip_link+'" '+
          'data-send="false" data-layout="box_count" data-width="50" data-show-faces="true"></div>')
          .append('<div class="g-plusone" data-size="tall" data-href="'+clip_link+'" data-annotation="bubble"></div>');

          if (window.FB){
              FB.init({
                  xfbml : true
              })
          }

          if(window.gapi){
            gapi.plusone.go();
          }

        }

        $('#clip-loading').remove();
          $('#clip-content').show();
          var key = response.key;
          var id = response.clipid;
          var clip_link = deconf.baseUrl+'c/'+id;
          var thumb = deconf.cdnBase+deconf.volumeId+'/'+key+'/thumb.jpg';
          $('#clip-share-popup .thumb').append(
            '<a href="'+clip_link+'" target="_blank"><img src="'+thumb+'" alt="clip thumb" /></a>'
          );

          if ($.browser.msie){
            $("#clip-share-popup .thumb").find('a').click(function(e){
                window.location = clip_link;
                e.preventDefault();
                return false;
            });
          }

          showClipSharingOptions(clip_link);
          
          var clip = null;
          
          var init = function () {
			ZeroClipboard.setMoviePath( deconf.baseUrl+'js/libs/zclip/ZeroClipboard10.swf' );
			clip = new ZeroClipboard.Client();
			clip.setHandCursor( true );
			
			clip.addEventListener('load', function (client) {
			});
			
			clip.addEventListener('mouseOver', function (client) {
				// update the text on mouse over
				clip.setText( $('#clip-short-link').val() );
			});
			
			clip.addEventListener('complete', function (client, text) {
			});
			
			clip.glue( 'copy-this-link', 'copy-this-link-container' );
		}
		
		init();
		

    }else if (clipType == 'open'){
        var id = response.clipid;
        $("#clip-loading").html('<a href="'+deconf.baseUrl+'c/'+id+'" target="_blank">Clip is ready click here to open</a>');
    }else if (clipType == 'print'){
        var id = response.clipid;
        $("#clip-loading").html('<a href="'+deconf.baseUrl+'c/'+id+'?show=print" target="_blank">Clip is ready click here to open it</a>');
    }
}

function onDragFinish(evt){
  $pageContainer
  .css('cursor','url("' + deconf.baseUrl + 'theme/images/drag-up.cur "),move');
  lastScrollPos = {'left' :  $(document).scrollLeft(),'top'  :  $(document).scrollTop()};
}

function closeClip(){
$('#clip-rect, #clip-rect-btn, #overlay-shadow').remove();
//shows all preclipped boxes
$('.clip-box').show().removeClass('hover');

        deactivateClip();
}

function showClipBtns(clipPos, clipId){
  $( $('#clip-rect-btn-tmpl').html() ).appendTo('body')
  .css('top', (clipPos.top-30) + 'px').css('left', (clipPos.left-10) + 'px');

  if(typeof(clipId) != undefined){
    $('#clip-rect-btn').attr('data-clipid', clipId);
  }else{
    $('#clip-rect-btn').removeAttr('data-clipid');
  }

  $('#clip-rect-btn .btn.share').click(function(evt){
    //open a popup, let it load the clip

    $($('#clip-share-popup-tmpl').html()).appendTo('body').dialog({
      'open':loadClip('share'),
      'width':550,
      'height':450,
      'modal':true,
      'title':'Share this clip',
      'close':function(){
        $('#facebook-jssdk').remove();
        $('#gplus-script').remove();
        $(this).remove();
        closeClip();
      }
    });
  });

  $("#clip-rect-btn .btn.open").click(function(evt){
        var clipId = $('#clip-rect-btn').attr('data-clipid');
        if(clipId){
            window.open (deconf.baseUrl+'c/'+clipId,'_blank');
        }else{
            $($('#clip-share-popup-tmpl').html()).appendTo('body').dialog({
              'open':loadClip('open'),
              'width':550,
              'height':450,
              'modal':true,
              'title':'Open this clip',
              'close':function(){
                $('#facebook-jssdk').remove();
                $('#gplus-script').remove();
                $(this).remove();
                closeClip();
              }
            });
        }
  });

  $("#clip-rect-btn .btn.print").click(function(evt){
      var clipId = $('#clip-rect-btn').attr('data-clipid');
        if(clipId){
            window.open (deconf.baseUrl+'c/'+clipId+'?show=print','_blank');
        }else{
          $($('#clip-share-popup-tmpl').html()).appendTo('body').dialog({
              'open':loadClip('print'),
              'width':550,
              'height':450,
              'modal':true,
              'title':'Print this clip',
              'close':function(){
                $('#facebook-jssdk').remove();
                $('#gplus-script').remove();
                $(this).remove();
                closeClip();
              }
          });
        }
  });
  
  $('#clip-rect-btn .btn.remove').click(function(evt){

        if (typeof(clipId) != 'undefined'){
            var clip_pgnum=$('.clip-box[data-clipid="'+clipId+'"]').attr('data-pgnum');
            $.getJSON(deconf.baseUrl+'clip/remove/'+clipId,
                function(response){
                    clearCache();
                    if (pageData[clip_pgnum].hasOwnProperty('clips')){
                        var newclips = [];
                        var x_0,x_1,y_0,y_1;
                        for (var idx in pageData[clip_pgnum]['clips']){
                            if (pageData[clip_pgnum]['clips'].hasOwnProperty(idx)){
                                if (pageData[clip_pgnum]['clips'][idx]['id']!=clipId){
                                    x_0 = pageData[clip_pgnum]['clips'][idx]['x0'];
                                    x_1 = pageData[clip_pgnum]['clips'][idx]['x1'];
                                    y_0 = pageData[clip_pgnum]['clips'][idx]['y0'];
                                    y_1 = pageData[clip_pgnum]['clips'][idx]['y1'];
                                    newclips.push({'x0':x_0,'x1':x_1,'y0':y_0,'y1':y_1,'id':clipId});
                                }
                            }
                        }
                        pageData[clip_pgnum]['clips'] = newclips;
                    }
                });
        }
	$("#.clip-box[data-clipid='"+clipId+"']").remove();
        closeClip();
  });
}

function onClipFinish(evt){
  $pageContainer.css('cursor', 'default');
  var area = $('#clip-rect').width() * $('#clip-rect').height();
  if(area < 200){
    closeClip();
    return;
  }
  //show a scissors icon which on click
  //opens a popup with the clip in it.
  var nope = function(evt){evt.preventDefault();evt.stopPropagation();}
  $('#clip-rect').mousedown(nope).mouseup(nope);

  $('<div id="clip-rect-close"></div>').appendTo('#clip-rect')
  .click(function(evt){
    closeClip();
    evt.stopPropagation();
    evt.preventDefault();
  });

  var clipPos = $('#clip-rect').offset();

  showClipBtns(clipPos);
}
var preventClick;
function onMouseUp(evt){
  preventClick = false;
  if(isDragging){
    $(window).trigger(deEvents.dragFinish);
    preventClick = true;
    isDragging = false;
  }

  if(isClipping){
    $(window).trigger(deEvents.clipFinish);
    preventClick = true;
    isClipping = false;
  }else{
    //clear any clipping
    closeClip();
  }
  $pageContainer.unbind('mousemove');
  if (deconf.isautoScroll) {
      $(window).unbind(deEvents.autoScroll).bind(deEvents.autoScroll,autoScroll);
      $(window).trigger(deEvents.autoScroll);
  }
  evt.preventDefault();
}

function activateClip(){
    $('#de-navbar .clip div').addClass('active');
    $('#de-navbar .clip').find('.label').addClass('active');
}

function deactivateClip(){
    $('#de-navbar .clip div').removeClass('active');
    $('#de-navbar .clip').find('.label').removeClass('active');
}

function onMouseMoveClip(evt){

    activateClip();
  //prepare clipping
  if(! isClipping){
    isClipping = true;
    closeClip(); //reset
    setCursor();
    //hide all clip boxes until clipping is complete
    $('.clip-box').hide();
    $clipRect = $('<div id="clip-rect"></div>').appendTo('#de-page-container');
    //if canvas exists make canvas tag else use div
    if(Modernizr.canvas){
      overlayShadow = $('<canvas id="overlay-shadow"></canvas>').appendTo('#de-page-container')
        .get(0);
    }else{
      overlayShadow = $('<div id="overlay-shadow"></div>').appendTo('#de-page-container')
        .get(0);
    }
    overlayShadow.width = $pageContainer.width();
    overlayShadow.height = $pageContainer.height();
  }
  //draw a box with border
  var x = (evt)? evt.pageX - pageOffset.left : 0;
	var y = (evt)? evt.pageY - pageOffset.top : 0;

    //set clip area in dual mode
    if (!isSingleView() && clickPage%2==0){
        if (x > getLevel(clickPage,de.zoom).width) return;
    }else if (!isSingleView() && clickPage%2==1){
        if (x < getLevel(clickPage,de.zoom).width) return;
    }



	//draw a box from x,y to clickPos.x, clickPos.y
	//if not clipBox then set it to 0,0
	clickPos = (clickPos) ? clickPos : {x:0,y:0};
	var w = x - clickPos.x;
	var h = y - clickPos.y;
	var topX=0,topY=0, ah = (h>0)?h:-h, aw = (w>0)?w:-w;
	$clipRect.width(aw).height(ah);
	if(w>0 && h>0){
	  topX = clickPos.x;
	  topY = clickPos.y;
	}
	if(w>0 && h<0){
	  topX = clickPos.x;
	  topY = y;
	}
	if(w<0 && h>0){
	  topX = x;
	  topY = clickPos.y;
	}
	if(w<0 && h<0){
	  topX = x;
	  topY = y;
	}
	$clipRect.css('top', topY +'px').css('left', topX +'px');

	evt && evt.preventDefault();

	if(Number(de.zoom) > 1){
    return; //don't draw a shadow in higher zoom as it gets CPU intensive
  }

	//draw overlay shadow using canvas or divs
	if(Modernizr.canvas){
	  var canvas = overlayShadow;
	  var ctx = canvas.getContext('2d');
		canvas.width = canvas.width; //clears it

		ctx.fillStyle = "rgba(0,0,0,0.2)";
		ctx.fillRect (0, 0, canvas.width, topY);
		ctx.fillRect (0, topY, topX, ah);
		ctx.fillRect (0, topY+ah, canvas.width, canvas.height-(topY+ah));
		ctx.fillRect (topX+aw, topY, canvas.width-(topX+aw), ah);
	}else{
	  var t,b,l,r;

		t = document.createElement('div');
		t.style.top = "0px";
		t.style.left = "0px";
		t.style.width = overlayShadow.width + "px";
		t.style.height = topY + "px";

		l = document.createElement('div');
		l.style.top = topY + "px";
		l.style.left = "0px";
		l.style.width = topX + "px";
		l.style.height = ah + "px";

		r = document.createElement('div')
		r.style.left = (topX + aw) + "px";
		r.style.top = topY + "px";
		r.style.width = (overlayShadow.width-(topX+aw)) + "px";
		r.style.height = ah + "px";

		b = document.createElement('div')
		b.style.top = (topY+ah)+"px";
		b.style.left = "0px";
		b.style.width = overlayShadow.width + "px";
		b.style.height = (overlayShadow.height-(topY+ah)) + "px";

		t.style.background =l.style.background =r.style.background = b.style.background = 'grey';
		b.style.filter = r.style.filter = l.style.filter = t.style.filter = "alpha(opacity=20)";
		b.style.position = r.style.position = l.style.position = t.style.position = 'absolute';
		$(overlayShadow).empty().append(t).append(l).append(r).append(b);
	}
}

function onMouseMoveScroll(evt){
  isDragging = true;
  var x = evt.screenX;
  var y = evt.screenY;
  var yScreenRatio = y / window.screen.height;
  var yDiff = yScreenRatio * window.screen.height;
  yDiff = (lastScreenPos.y * window.screen.height - yDiff) ;
  if(lastScrollPos){
      yDiff = lastScrollPos.top + yDiff ;
  }
  //top down scrolling
  $(document).scrollTop(yDiff);
  var xScreenRatio = x / window.screen.width;
  var xDiff = xScreenRatio * window.screen.width;
  xDiff = (lastScreenPos.x * window.screen.width - xDiff) ;
  if(lastScrollPos){
      xDiff = lastScrollPos.left + xDiff ;
  }
  $(document).scrollLeft(xDiff);
  evt.preventDefault();
}

function onMouseDown(evt){
  var x = evt.pageX;
	var y = evt.pageY;
	//get it relative to page

	x = x - pageOffset.left;

	y = y - pageOffset.top;

	var yScreen = evt.screenY;

        var xRatio = x / currentLevel.width;
        if (!isSingleView())
        var xRatio = x / (currentLevel.width*2);

	var yRatio = y / currentLevel.height;
  clickPos = {'x': x,'y': y};
  clickPosRatio = {'x': xRatio, 'y': yRatio};
  lastScreenPos = {'x': evt.screenX / window.screen.width, 'y': yScreen / window.screen.height};
  //bind to scroll when zoomed in otherwise bind to clipping
  if(Number(de.zoom) > 1 && !isClipping){
	    $pageContainer.css('cursor',
	      'url("' + deconf.baseUrl + 'theme/images/drag-down.cur "),move')
	     .unbind('mousemove').mousemove(onMouseMoveScroll);
   }

   if(isClipping || Number(de.zoom) == 1){
    $pageContainer.unbind('mousemove').mousemove(onMouseMoveClip);
   }

   checkClickedPage(x);

   lastScrollPos = {'left':$(document).scrollLeft(), 'top':$(document).scrollTop()};
   evt.preventDefault();
}


function checkClickedPage(x){
   //check clicked page for clipping in dual mode
   if (x > currentLevel.width){
       clickPage = Number(de.page) + 1;
   }else{
       clickPage = Number(de.page);
   }
}

var headerLeftMarginTimeout;

function onPageScroll(evt) {
  if(Modernizr.touch) {
      var window_top_offset  = $(window).scrollTop();
      var window_left_offset = $(window).scrollLeft();
      var pageOffset =  $('#de-chunks-container').offset();
      var move_left = (de.zoom == 1) ? (pageOffset.left) : (window_left_offset); 
      if(window_top_offset > 90) {      
          $('#de-navbar').css({'top':((window_top_offset))+'px','left':move_left+'px'});
      } else { 
          $('#de-navbar').css({'top':navbar_top+'px','left':move_left+'px'});
      } 
      if(de.zoom >= 1) { 
          if($(window).scrollLeft()+$('#de-navbar').width() < $('#de-page-wrapper').width()) {
            $('#de-navbar').css('left',move_left+'px');
          } 
      }
  } else {
      //if page is scrolled down, fix the navbar at the top
      navBarOffset = (navBarOffset) ? navBarOffset : $('#de-navbar').offset();

      if( $(window).scrollTop() >= navBarOffset.top || $(window).scrollLeft() > navBarOffset.left){
        if(!navBarFixed){
          navBarFixed = true;
          $('#de-navbar').addClass('fixed')
          .css('margin-left', '')
          .css('left', navBarOffset.left+'px')
          .after('<div class="de-navbar-proxy"></div>');

          //$("#de-sidebar-wrapper").addClass('fixed');
        }
      }else{
        //unfix the navbar
        if(navBarFixed){
          navBarFixed = false;
          $('#de-navbar').removeClass('fixed').siblings('.de-navbar-proxy').remove();

          //$("#de-sidebar-wrapper").removeClass('fixed');
        }
      }
  }

  showVisibleChunks();
}

function showPreClipped() {
  //clean first
  $('.clip-box').remove();

  renderPreClip(pageData[de.page].clips,false);
    if (!isSingleView()){
        if (pageData.hasOwnProperty(Number(de.page)+1)){
            renderPreClip(pageData[Number(de.page)+1].clips,true);
        }
    }
}

function renderPreClip(clips, dual){
    //read the clips from pageData
  //draw divs which on mouseover shows
  //clipping toolbox

  //var clips = pageData[de.page].clips,
  var num_clips = clips.length,
      levelW = Number(currentLevel.width),
      levelH = Number(currentLevel.height),
      clip, clipBox, clipBoxH, clipBoxW;
  var closeTimer;

  var clipMouseOver = function(evt){
    var $clip = $(evt.currentTarget);
    clearTimeout(closeTimer);

    if($clip.css('display') == 'none'){
      return;
    }

    if($('#clip-rect-btn').length){
      $('#clip-rect-btn').remove();
      $('.clip-box').removeClass('hover');
    }
    showClipBtns($clip.offset(), $clip.attr('data-clipid'));

    $('#clip-rect-btn').unbind('mouseover').unbind('mouseout')
    .mouseover(function(){
      clearTimeout(closeTimer);
    })
    .mouseout(function(){
      closeTimer = setTimeout(closeClip, 10);
    });
  };

  var clipMouseOut = function(evt){
    var $clip = $(evt.currentTarget);

    //prevent the onmouseout from firing when hidden
    if($clip.css('display') == 'none'){
      return;
    }
    $clip.addClass('hover');
    closeTimer = setTimeout(closeClip, 10);
  };

  for(var idx=0; idx < num_clips; idx += 1){
    clip = clips[idx];
    clipBox = document.createElement('div');
    clipBox.setAttribute('data-clipid', clip.id);
    clipBoxH = levelH * (Number(clip.y1) - Number(clip.y0));
    clipBoxW = levelW * (Number(clip.x1) - Number(clip.x0));
    clipBox.setAttribute('class', 'clip-box');
    clipBox.style.width = clipBoxW + 'px';
    clipBox.style.height = clipBoxH + 'px';
    clipBox.style.top = (levelH * Number(clip.y0)) + 'px';
    if (dual){
        clipBox.style.left = (levelW * Number(clip.x0)) + levelW + 'px';
        clipBox.setAttribute('data-pgnum',Number(de.page)+1);
    }else{
        clipBox.style.left = (levelW * Number(clip.x0)) + 'px';
        clipBox.setAttribute('data-pgnum',Number(de.page));
    }

    $(clipBox).mouseover(clipMouseOver)
      .mouseout(clipMouseOut);

    $pageContainer.append(clipBox);
  }
}

function prepareForClipping(){
  if($('#overlay-shadow').length > 0){
	    return;
	}
  clickPos = {x:0,y:0};
  onMouseMoveClip(undefined);
  $pageContainer.css('cursor','crosshair');
  activateClip();
}

function cancelClipping(){
  if($('#overlay-shadow').length > 0){
	    isClipping = false;
	    closeClip();
	    return;
	}
}

function preloadPage(){

  if(de.allPageDataLoaded){
    var pages, isSingle, level;
    if(isSingleView()){
      pages = [Number(de.page)+1, Number(de.page)-1];
    }else{
      pages = [Number(de.page)+2, Number(de.page)+3, Number(de.page)-1, Number(de.page)-2];
    }
    for(var i = 0; i < pages.length; i += 1){
      level = getLevel(pages[i], 1);
      if(level){
        for(var chunkIdx=0; chunkIdx < level.chunks.length; chunkIdx += 1){
          var img = new Image();
          img.src = level.chunks[chunkIdx].url;
        }
      }
    }


  }else{
    $.getJSON(deconf.baseUrl+'pagemeta/get/'+deconf.volumeId+'/1-'+deconf.numPages,
    function(response){
      pageData = response;
      de.allPageDataLoaded = true;
      $(window).trigger(deEvents.pageDataLoaded);
    });
  }



}

function onPageClick(evt){
  if(Number(de.zoom) == 1 && !preventClick){
    window.location.hash = de.mode+'/'+de.page+'/2';
  }
}

function onShowThumb(){
    var end=1;
    var sidebar = $("#de-thumb-container");

    var displayAreaHeight = $("#de-thumb-container").height() + $("#de-thumb-container").scrollTop() + 250;

    var totalPageHeight = 0;
    for (end =1; end <= deconf.numPages; end++){
        if (pageData.hasOwnProperty(end)){
            totalPageHeight += Number(pageData[end].levels.thumbs.height) + 17;
        }else{
            totalPageHeight += 17;
        }

        if (totalPageHeight>displayAreaHeight) break;
    }

    for (var page=$(".de-thumb").length+1; page <= end; page++){
        if (pageData.hasOwnProperty(page)){

            var thumb = document.createElement('div');
            thumb.className = 'de-thumb';
            thumb.setAttribute('pgnum', page);

            var thumb_img = new Image();
            thumb_img.src = pageData[page]['levels']['thumbs']['chunks']['0']['url'];

            var thumb_page_num = document.createElement('div');
            thumb_page_num.innerHTML=page;

            thumb.appendChild(thumb_img);
            thumb.appendChild(thumb_page_num);

            sidebar.append(thumb);
        }
    }


    $(".de-thumb")
        .unbind('mouseover').bind('mouseover',function(evt){
            var pagenum = $(this).attr('pgnum');
            var img = new Image();
            img.src=pageData[pagenum]['levels']['level0']['chunks']['0']['url'];
            var width = pageData[pagenum]['levels']['level0']['chunks']['0']['width'];
            var height = pageData[pagenum]['levels']['level0']['chunks']['0']['height'];
            $("#de-hover-thumb-container").height(height).width(width).empty().append(img).show();
        })
        .unbind('mouseout').bind('mouseout',function(){
            $("#de-hover-thumb-container").hide();
            $("#line").remove();
        })
        .unbind('click').bind('click',function(){
            window.location.hash=de.mode+'/'+$(this).attr('pgnum')+'/'+de.zoom;
        });

        firstPage = pageData[1];
}


function isSingleView(){
    return (de.mode=='page' || de.page==1 || de.page==deconf.numPages) ? true : false;
}

function loadSections(){
    $.getJSON(deconf.baseUrl+'pagemeta/getSection/'+deconf.volumeId,
    function(response){
        sectionData = response;
       $(window).trigger(deEvents.sectionsLoaded);
    });
}

function sectionsLoaded(){
    var section_wrapper = $('#de-section-wrapper').empty();
    for (var section in sectionData){
//        var section_div = document.createElement('div');
//        section_div.className = 'de-section';
//        section_div.innerHTML = section;
//        section_div.setAttribute('secname', section);
//        section_wrapper.append(section_div);

        section_wrapper.append('<div class="grid_4 alpha">'+
                                  '<button class="btn dropdownButton nofloat" style="width:150px">'+
                                    '<div><span class="label">'+section+'</span></div>'+
                                  '</button>'+
                                '</div>'+
                                '<div style="clear:both"></div>');
    }

    $(".de-section").live('click',function(){
        window.location.hash = DE.mode+'/'+sectionData[$(this).attr('secname')]['0']+'/'+DE.zoom;
    });
    $(window).trigger(deEvents.adjustSidebar);
}

function autoScroll(){
        pageWidth=0,
        pageHeight=0,
        screenWidth=0,
        screenHeight=0,
        screenMouseX=0,
        screenMouseY=0,
        pageTop=0,
        pageLeft=0,
        avgScrollLeft=0,
        avgScrollTop=0,
        avgScrollRight=0,
        avgScrollBottom=0;

    $("#de-page-container")
        .unbind('mouseenter')
        .bind('mouseenter',function(evt){
            calculationForAutoScroll(evt);
        })
        .unbind('mousemove')
        .bind('mousemove',function(evt){
            if (de.zoom>1){
                var posDiffX = evt.clientX - screenMouseX;
                var posDiffY = evt.clientY - screenMouseY;

                if ((posDiffX)>0 && avgScrollRight){
                    //scroll right
                    $(window).scrollLeft($(window).scrollLeft() + (posDiffX * avgScrollRight));
                }else if ((posDiffX)<0 && avgScrollLeft){
                    //scroll left
                    $(window).scrollLeft($(window).scrollLeft() - (Math.abs(posDiffX) * avgScrollLeft));
                }

                if ((posDiffY>0) && avgScrollBottom){
                    //scroll bottom
                    $(window).scrollTop($(window).scrollTop() + (posDiffY * avgScrollBottom));
                }else if ((posDiffY<0) && avgScrollTop){
                    //scroll top
                    $(window).scrollTop($(window).scrollTop() - (Math.abs(posDiffY) * avgScrollTop));
                }
                calculationForAutoScroll(evt);
                evt.preventDefault();
            }
        })
        ;

}

function calculationForAutoScroll(evt){
    pageWidth = $("#de-page-container").width(),
    pageHeight = $("#de-page-container").height(),
    screenWidth = $(window).width(),
    screenHeight = $(window).height(),
    screenMouseX = evt.clientX,
    screenMouseY = evt.clientY,
    pageTop = $("#de-page-container").offset().top - $(window).scrollTop(),
    pageLeft = $("#de-page-container").offset().left - $(window).scrollLeft();

    if (pageTop<0){
        avgScrollTop = Math.abs(pageTop) / screenMouseY;
        avgScrollBottom = (pageHeight - (Math.abs(pageTop) + screenHeight)) / (screenHeight - screenMouseY);
    }else{
        avgScrollTop = 0;
        avgScrollBottom = (pageHeight > screenHeight) ? ((pageHeight - screenHeight + pageTop) / (screenHeight - screenMouseY)) : 0;
    }

    if (pageLeft<0){
        avgScrollLeft = Math.abs(pageLeft) / screenMouseX;
        avgScrollRight = (pageWidth - (Math.abs(pageLeft) + screenWidth)) / (screenWidth - screenMouseX);
    }else{
        avgScrollLeft = 0;
        avgScrollRight = (pageWidth > screenWidth) ? ((pageWidth - screenWidth + pageLeft) / (screenWidth - screenMouseX)) : 0;
    }
}

function showLoginForm(){
    $($("#de-subscribe-login-box-tmpl").html())
        .appendTo('body').dialog({
           'autoOpen': true,
           'center':true,
           'modal':true,
           'width':550,
           'height':'auto',
           'close': function(){
               $(this).remove();
           }
        });

        $("#de-subscribe-login-box #login-subscribe-login").unbind('click').bind('click',function(){

        });

        $("#de-subscribe-login-box #cancel-subscribe-login").unbind('click').bind('click',function(){
            $("#de-subscribe-login-box").dialog('destroy').remove();
            $(window).trigger(deEvents.showAuthBox);
        })
}

function showComments(){


    if ($("#de-comments").css('display')=='none')
        $("#de-comments").show();
    else if ($("#de-comments").css('display')=='block')
        $("#de-comments").hide();

    if ($("#de-comments").length==0){
        var offset = $("#de-comments-btn").offset();
        $($("#de-comments-tmpl").html())
            .css({'left':offset.left+'px'})
            .css({'top':offset.top+25+'px'})
            .appendTo('body');
        $("#volume-fb-comments").attr('data-href',deconf.baseUrl+deconf.volumeId);
        //loadScript(document, 'script', 'facebook-jssdk', '//connect.facebook.net/en_US/all.js#xfbml=1')
        if (window.FB){
            FB.init({
                xfbml : true
            })
        }

        $("#de-comments .title .close").click(function(){
           $("#de-comments") .hide();
        });
    }
}


function loadPlugins(){
    page_key = pageData[de.page].key;
    //see which plugins are to be loaded
    //load their attributes
    //and show them as they are loaded
    var plugins = [];
    //for caching responses
    if(typeof(DE.plugincache) == 'undefined') DE.plugincache = {};
    if(typeof(DE.plugincache[page_key]) == 'undefined'){
        DE.plugincache[page_key] = {};
    }

    for(var plugin in DE.plugins){
        if(!DE.plugins.hasOwnProperty(plugin)) continue;
        plugins.push(plugin);
    }

    if (DE.plugincache[page_key]['plugin']){
        showPlugin(DE.plugincache[page_key]['plugin'],"left");
    }else{
        getPlugins(page_key,plugins,"left")
    }

    if (!isSingleView()){
        right_page_key = pageData[Number(de.page)+1].key;

        if(typeof(DE.plugincache[right_page_key]) == 'undefined'){
            DE.plugincache[right_page_key] = {};
        }

        if (DE.plugincache[right_page_key]['plugin']){
            showPlugin(DE.plugincache[right_page_key]['plugin'],"right");
        }else{
            getPlugins(right_page_key, plugins, "right")
        }
    }
}

function getPlugins(key,plugins,pageside){
    $.getJSON(deconf.baseUrl+ 'attributes/getv3/'+key+'/'+plugins.join('/'),
            function(response){
               DE.plugincache[key]['plugin'] = response;
               showPlugin(response,pageside);
            });
}

function showPlugin(response, pageside){
    for (var plugin in response){
       var num_items = response[plugin].length;
       var item;
       for(var i=0; i<num_items; i+=1){
            if (pageside=="left"){
                if (response[plugin][i]["attributes"]["pagekey"]!=pageData[de.page].key) return;
            }
            if (pageside=="right"){
                if (response[plugin][i]["attributes"]["pagekey"]!=pageData[Number(de.page)+1].key) return;
            }
           item = response[plugin][i];
           DE.plugins[plugin].onShow(item, pageside);
           loadlibrary(DE.plugins[plugin].requirelibs);
       }
   }
}

function loadlibrary(lib_array){
    var loadScript = function(d, s, id, src) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) {return;}
            js = d.createElement(s);js.id = id;
            js.src = src;
            fjs.parentNode.insertBefore(js, fjs);
          };
    if (lib_array.length){
        for (i=0; i<lib_array.length; i++){
            loadScript(document,'script',lib_array[i].id, lib_array[i].src);
        }
    }
}

function drawAugmentedBox(x0,y0,x1,y1, elem, pageside){
    var level= currentLevel;
    var h = Number(level.height);
    var w = Number(level.width) ;
    var box;
    if(elem){
        box = document.createElement(elem);
    }else{
        box = document.createElement('div');
    }
    var boxheight = (y1 * h - y0 * h);
    var boxwidth = (x1 * w - x0 * w);
    box.style.position = 'absolute';
    box.style.display = 'block';
    box.style.top = (y0 * h) + 'px';

    if (pageside=="left"){
        box.style.left =(x0 * w) + 'px';
    }else if (pageside=="right"){
        box.style.left = ((x0 * w) + w) + 'px';
    }

    box.style.height=boxheight+'px';
    box.style.width=boxwidth+'px';
    box.style.backgroundImage='url("'+deconf.baseUrl+'theme/images/Transparent.gif")';
    box.style.zIndex = 11;
    box.setAttribute('class', 'augmented-box');
    return box;
}

function showCommentCount(){
    var url = deconf.baseUrl+deconf.volumeId;
    $.getJSON('http://graph.facebook.com?ids='+escape(url)+'&callback=?',
    function(response){
        var count = Number(response[url]['comments']);
        var commentStr = (count > 1) ? count + " comments" :
            (count == 1) ? '1 comment' : 'Add comment';
        $('#de-comments-btn .label').text(commentStr);
    });

}

function showFeedback(){
    if ($("#de-feedback").length > 0){
        $("#de-feedback").remove();
        return;
    }

    $($("#de-feedback-tmpl").html())
        .css({'bottom':$("#de-footer").height()+'px'})
        .appendTo('body');

    $("#de-feedback .title .close").click(function(){
        $("#de-feedback").remove();
    });
    if (window.FB){
        FB.init({
            xfbml : true
        })
    }

    $("#de-feedback .btn.feedback-send").click(function(){
        if ($("#de-feedback .feedback-text").val().trim()==''){
            return;
        }
        $("#de-feedback .btn.feedback-send").html(
          '<img class="loader" style="float:left;" src="/theme/images/loader.gif" alt=""/>');
        $("#de-feedback .btn.feedback-cancel").remove();
        $.post(deconf.baseUrl + 'feedback/send',
            {
              'response' : $("#de-feedback .feedback-text").val().substr(0, 5000),
              'email'   : $("#de-feedback .feedback-email").val(),
              'url': DEConfig.baseUrl
            },
            function(response){
                $("#de-feedback").remove();
            });
    });

    $("#de-feedback .btn.feedback-cancel").click(function(){
       $("#de-feedback").remove();
    });
}

function changeTitle(evt)
{
    var t_id = $('#titles-select').val();
    window.location.href = deconf.baseUrl + 't/' +t_id + '/latest';

}

function getCookies(c_name){
    var i,x,y, cookies = document.cookie.split(";");
    for (i=0;i<cookies.length;i++){
        x = cookies[i].substr(0,cookies[i].indexOf("="));
        y = cookies[i].substr(cookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,""); //trim
        if (x==c_name){
            return unescape(y);
        }
    }
    return '';
}

function checkCookies(){
    var cookie = getCookies('de');
    if (cookie!=''){
        cookie = cookie.split(',');
        deconf.showSidebar = (cookie[0]=='true') ? true : false;
        deconf.isautoScroll = (cookie[1]=='true') ? true : false;

        if (deconf.isautoScroll){
            $(window).trigger('autoScrollEvent');
        }
    }else{
        $(window).trigger('showSidebar');
    }
    $(window).unbind(deEvents.renderPage, checkCookies);
}

function setCookies(c_name,value,exdays){
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + "; path=/";
}

function changepdf(){
    var pdflink = deconf.baseUrl+'pdf/get/'+deconf.volumeId+'/'+de.page;
    $('#de-page-toolbox .de-pdf-link').html(
        '<a href="'+pdflink+'" title="Download this page"><img src="'+deconf.baseUrl+
            'theme/images/Transparent.gif" width="55" height="20" /></a>'
    );
}


function showHideAds(){
    if (deconf.titleType=='comic'){
        if (de.zoom>1){
            $("#de-side-ad").hide();
            $("#de-right-small-ad").hide();
        }else{
            $("#de-side-ad").show();
            $("#de-right-small-ad").show();
        }
    }
}

function removeAutoHideElements(){
    $(".autoclose").remove();
}

function checkLogin(){
    $.getJSON(deconf.authBase+'api/checklogin?callback=?',
    function(response){
        if (response.id){
            deconf.loggedin = true;
            userdata = response;
        }else{
            $(".btn.subscribe").css('visibility','visible');
        }
        loginChecked();
    });
}

function checkAuth(){
    $.getJSON(deconf.authBase+'api/checkauth/'+deconf.volumeId+'?callback=?',
    function(response){
        if (response.token){
            setCookies('detoken',response.token);
            deconf.isAuth = true;
        }
        authChecked();
    });
}



function loginChecked(){
    if (deconf.needsAuth){
        if (deconf.loggedin){
            $(".de-login-content").html('<img src="'+deconf.baseUrl+'theme/images/loader.gif" />'+
    				    '<span>Authenticating...</span>');
            checkAuth();
        }else{
            $(".de-login-content")
            .html('you must be logged in to read this volume'+
                    '<button class="btn nofloat login">'+
                    '<div><span class="label">Register/Login</span></div>'+
                    '</button>'
                  );
             $(".de-login-content .btn.login").click(showSignIn);
        }
    }else if(deconf.loggedin){
        showuserinfo();
    }
}

function authChecked(){
    if (deconf.isAuth){
        $('#de-subscribe-login-box').hide();
        $("#de-navbar").show();
        $("#de-page-toolbox").show();
        $("#de-sidebar-wrapper").show();
        $("#de-sidebar-handler").show();
        $("#de-bottom-ad").show();
        showuserinfo();
        documentReady();
    }else{
        $("#de-sidebar-handler").remove();
        $("#de-sidebar-wrapper").remove();
        //show Purchase Volume Option
        var html = '<div class="de-user-id">Welcome '+userdata.email+
                    ' <a href="' + deconf.authBase +'/user/logout?ru='+deconf.baseUrl+'r/'+deconf.volumeId+'">Not you</a></div>';
                    
        $(".de-login-content")
            .html(html + 'you are not authorized to read this volume<br><br>'+
                    '<button class="btn nofloat purchase">'+
                    '<div><span class="label">Purchase this volume</span></div>'+
                    '</button>'
                  );
        $(".de-login-content .btn.purchase").click(showpricelist);
    }
}

function showpricelist(){
    $(".de-login-content").html('<img src="'+deconf.baseUrl+'theme/images/loader.gif" />'+
		    '<span>Wait...</span>');
	$.getJSON(deconf.baseUrl+'api/getpricelist/'+deconf.volumeId,
    function(response){
        makepricelist(response);
    });
}

function makepricelist(response){

    var html;
    var pricelist = $("#de-price-list-tmpl").html();
    $('.de-login-content').html(pricelist);
    
    pricelist = $("#de-price-list");
    $(pricelist).find('.de-price-head').after('<div class="de-price">'+
                '<div class="de-price-left">'+
                    '<input type="radio" checked="true" name="price" data-offid="0" value="'+(response['volume']['price']/100)+'" />'+
                '</div>'+
                '<div class="de-price-right">'+
                    'Purchase this volume @ '+ 
                    ' <img src="' + deconf.baseUrl + 'theme/images/inr_symbol.png" width="16" height="16" />' +
                    (parseFloat(response['volume']['price']/100).toFixed(2)) +
                '</div>'+
                '<span class="clear"></span>'+
            '</div>');
    
    for(var rule in response['title']){
        html = '<div class="de-price">'+
                    '<div class="de-price-left">'+
                        '<input type="radio" name="price" data-offid="'+response['title'][rule]['offid']+'" value="'+(response['title'][rule]['price']/100)+'" />'+
                    '</div>'+
                    '<div class="de-price-right">'+
                        response['title'][rule]['volumes'] + ((response['title'][rule]['volumes']>1) ? ' volumes' : ' volume') + 
                        ' @ ' + 
                        ' <img src="' + deconf.baseUrl + 'theme/images/inr_symbol.png" width="16" height="16" />' +
                        (parseFloat(response['title'][rule]['price']/100).toFixed(2)) +
                    '</div>'
                    '<span class="clear"></span>'+
                '</div>';
        $(pricelist).find(".de-price-title").after(html);
    }
    
    $(pricelist).find(".de-amount-left").html('Amount:<span data-offid="0">'+
    '<img src="' + deconf.baseUrl + 'theme/images/inr_symbol_red.png" width="16" height="16" />' +
    (parseFloat(response['volume']['price']/100).toFixed(2))+' ($ '+
    ((parseFloat(response['volume']['price']/100) * parseFloat(deconf.dval)).toFixed(2))+')</span>');
    
    /*$(pricelist).find(".de-amount-right").html('<select id="paynow">'+
                        '<option value="">Select Payment</option>'+
                        '<option value="ccavenue">CCAvenue</option>'+
                        '<option value="paypal">Paypal</option>'+
                    '</select>');*/
    
    $(pricelist).find(".de-amount-right").html('<button class="btn nofloat selectpayment">'+
                                                '<div><span class="label">Select Payment Option</span></div>'+
                                              '</button>');
                                              
    $(".btn.selectpayment").click(function(){
        if ($("#de-payment-option").length){
            $("#de-payment-option").remove();
            return;
        }
        var offset = $(this).offset();
        $($("#de-payment-option-tmpl").html())
            .css({'left':offset.left+'px','top':offset.top+20+'px','position':'absolute'})
            .appendTo('body');
        $("#de-payment-option").find('li:eq(0)').click(function(){
            var offid = $(pricelist).find('.de-amount').find('.de-amount-left').find('span').attr('data-offid'); 
            window.location.href= deconf.authBase + 'paypal/show/' + deconf.volumeId + '/' + offid;       
        });
        $("#de-payment-option").find('li:eq(1)').click(function(){
            var offid = $(pricelist).find('.de-amount').find('.de-amount-left').find('span').attr('data-offid'); 
            window.location.href= deconf.authBase + 'ccavenue/checkout/' + deconf.volumeId + '/' + offid;         
        });
    });
  
    $(pricelist).find('input:radio').each(function(){
        $(this).click(function(){
            var radio = $(this);
            $(pricelist)
                .find('.de-amount')
                .find('.de-amount-left')
                .find('span')
                .attr('data-offid',radio.attr('data-offid'))
                .text((parseFloat(radio.val())).toFixed(2)+' ($ ' +
                        ((parseFloat(radio.val())*parseFloat(deconf.dval)).toFixed(2)) + ')')
                .prepend('<img src="' + deconf.baseUrl + 'theme/images/inr_symbol_red.png" width="16" height="16" />');
        })
    });
    
    $(pricelist).find(".de-amount").find('#paynow').change(function(){
        var option = $(this).val();
        var offid = $(pricelist).find('.de-amount').find('.de-amount-left').find('span').attr('data-offid');        
        if (option=='paypal'){
            window.location.href= deconf.authBase + 'paypal/show/' + deconf.volumeId + '/' + offid;
        }else if (option=='ccavenue'){
            window.location.href= deconf.authBase + 'ccavenue/checkout/' + deconf.volumeId + '/' + offid;            
        }
    });
}

function showSignIn(){
	if (!deconf.loggedin){
	    window.location.href = deconf.authBase + 'user/login?ru=' + deconf.baseUrl + 'r/' + deconf.volumeId + '&td=' + deconf.titleId; 
	}
}

function loadauth(){
    $("#de-signin-box").append('<iframe src="'+deconf.authBase+'" frameborder="0" marginheight="0" marginwidth="0" width="750" height="550"></iframe');
}

function closesignin(){
    $("#de-signin-box").dialog('destroy');
    $("#de-signin-box").remove();
    checkLogin();
}

function addUserClip(response){
    if (deconf.loggedin){
        var key = response.key;
        var id = response.clipid;
        var clip_link = deconf.baseUrl+'c/'+id;
        var thumb = deconf.cdnBase+deconf.volumeId+'/'+key+'/thumb.jpg';
        $.getJSON(deconf.authBase+'api/setuserclip?callback=?',
		{
			'link':clip_link,
			'thumb':thumb,
			'clipid':id
		},
            function(response){});
    }
}

function showuserinfo(){        
    $("#de-user .login").remove();
    $("#de-user").append('<div class="de-user-wrapper">'+
                            '<div class="de-user-detail">'+
                                '<div class="de-user-name">'+
                                    '<!--<a href="'+deconf.authBase+'user/library" target="_blank">-->'+
                                        '<span title="'+userdata.email+'">'+userdata.email.substr(0,14)+'...</span>'+
                                    '<!--</a>-->'+
                                '</div>'+
                                '<div class="de-user-desc">'+
                                    '<span><a href="'+deconf.authBase+'user/library" target="_blank">My Library</a></span> &nbsp;&nbsp;'+
                                '</div>'+
                            '</div>'+
                        '</div>');
    $("#de-user").css({'background-color':'#fff'});  
    $("#de-user .subscribe").click(openSubscribe);
    makesale();            
    checknotifier();
    getlibrarystatus();
}

function makesale(){
    $.getJSON(deconf.authBase+'api/sale/'+deconf.volumeId+'/'+deconf.titleId+'?callback=?',
    function(response){
        
    });
}

function addtolibrary(){
    $.getJSON(deconf.authBase+'api/addtolibrary/'+deconf.volumeId+'?callback=?',
    function(response){
        if (response.result=="true"){
            window.location = deconf.authBase + 'user/library';
        }
    });
}

function getlibrarystatus(){
    $.getJSON(deconf.authBase+'api/getlibrarystatus/'+deconf.volumeId+'?callback=?',
    function(response){
        if (response.result=="false"){            
            $("#de-navbar .btn.subscribe")
                .unbind('click')
                .addClass('library').removeClass('subscribe')
                .bind('click',addtolibrary)
                .css('visibility','visible')
                .find('.label').text('Add to library');
        }else{
            $("#de-navbar .btn.subscribe")
                .unbind('click')
                .addClass('library').removeClass('subscribe')
                .bind('click',function(e){
                    window.location.href = deconf.authBase + 'user/library';
                })
                .css('visibility','visible')
                .find('.label').text('My library');
        }
    });
}

function checknotifier(){
    $.getJSON(deconf.authBase+'api/checknotifier/'+deconf.titleId+"?callback=?",
    function(response){
        if (response.hasOwnProperty('notifies')){
            if (response['notifies']){
               openSubscribe();
            }
        }
    });
}

function openSubscribe(){
if ($("#de-subscription-box").length > 0){
    $("#de-subscription-box").remove();
    return;
}
var clientWidth = document.body.clientWidth;
$($('#de-subscription-box-tmpl').html())
.appendTo('body')
.css({'left':(clientWidth/2-250)+'px','top':'300px','position':'fixed'});

if (typeof(userdata)!="undefined" && typeof(userdata.email)!=undefined){
    $('.subscription-email').val(userdata.email);
}
$('#de-subscription-box .message').hide();

   $("#de-subscription-box .title .close").click(openSubscribe);
  $('#de-subscription-box .btn.submit').unbind('click').click(
	function(evt){
		var name = $('.subscription-name').val();
		var email = $('.subscription-email').val();
		var titles = [DEConfig.titleId];
		var regexp= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		//check for valid values
		if(regexp.test(email)){
		    $('#de-subscription-box .list-form').hide();
		    $("#de-subscription-box .wait").show();
			  $.post(DEConfig.baseUrl + 'subscriber/add',
			  {'name': name,
			  'email': email,
			  'titles': titles.join(',')},
			  function(response){
			    $("#de-subscription-box .wait").hide();
			    $('#de-subscription-box .message').show();
			    $('#de-subscription-box .message h3').text('Thanks '+name);
			  }
			);
		}else{
		    $('.subscription-info').text('Invalid email, please check');
		}
	}
);

}
  

function showSigninPage(){
    $("#de-navbar").hide();
    $("#de-page-toolbox").hide();
    $("#de-sidebar-wrapper").hide();
    $("#de-sidebar-handler").hide();
    $("#de-bottom-ad").hide();

    $($("#de-subscribe-login-box-tmpl").html())
        .appendTo('body');
    checkLogin();
}

function prevPage(){
    if (DE.mode=='page'){
        var prevP = Number(DE.page) - 1;
    }else{
        var prevP = Number(DE.page) - 2;
    }
      if(prevP < 1) {
        var prevP = 1;
      }
      window.location.hash = DE.mode+'/'+prevP+'/'+DE.zoom;
}

function nextPage(){
    if (DE.mode=='page'){
        var nextP = Number(DE.page) + 1;
    }else{
        if (DE.page==1){
            var nextP = Number(DE.page) + 1;
        }else{
            var nextP = Number(DE.page) + 2;
        }
    }
    if(nextP > DEConfig.numPages) {
        if (DEConfig.numPages%2==0)
            var nextP = DEConfig.numPages;
        else if (de.mode=='dual')
            var nextP = DEConfig.numPages-1;
    }
    window.location.hash = DE.mode+'/'+nextP+'/'+DE.zoom;
}

function onTap(evt) {
        var touch = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0];
        var x = touch.pageX;
	var y = touch.pageY;
        x = x - pageOffset.left;
        y = y - pageOffset.top;

       var yScreen = evt.screenY;

        var xRatio = x / currentLevel.width;
        if (!isSingleView())
        var xRatio = x / (currentLevel.width*2);
        var yRatio = y / currentLevel.height;
        clickPos = {'x': x,'y': y};
        clickPosRatio = {'x': xRatio, 'y': yRatio};
        lastScreenPos = {'x': evt.screenX / window.screen.width, 'y': yScreen / window.screen.height};

        if(Number(de.zoom) == 1 && !preventClick) {
            window.location.hash = de.mode+'/'+de.page+'/2';

        } else if(Number(de.zoom) == 2 && !preventClick) {
            window.location.hash = de.mode+'/'+de.page+'/1';

        }

}
var navbar_top;
var touch_dist_x;
var touch_dist_y;
var screen_width;

function documentReady() {
  if(deconf.emulator_demo) {
      screen_width = 768;
  } else {screen_width = screen.width;}
  if(Modernizr.touch) { 
    $('#de-page-wrapper').css('min-width',screen_width);
    $('#de-page-wrapper').width(screen_width);
    $('body').css({'min-width':'0px','position':'relative'});
    $('#de-sidebar-handler').remove();
    $('#de-sidebar-wrapper').remove();
    if(screen_width >= 600) {
        $('#de-container').css('margin-top','85px');
        $('.page-link').css('display','block');
        $('.top_Ad').css('margin-left',((screen_width)/2 -364)+'px');
        $('#de-header').after('<div style="clear:both;display: block;height:40px;"></div>');
        navbar_top = 90;
        touch_dist_x = 80;
        touch_dist_y = 80;
    } else {
        //$('#de-container').css('margin-top','30px');
        $('#de-top-banner').remove();           // screen width chk
        $('#de-top-ad').remove();
        $('#de-container').css('margin-top','25px');
        $('#de-header').after('<div style="clear:both;display: block;height:20px;"></div>');
        navbar_top = 0;
        touch_dist_x = 15;
        touch_dist_y = 15;
    }
    $('#de-side-ad').remove();
    $('#de-bottom-ad').remove();
    $('#de-footer').remove();
    $('#de-page-toolbox').remove();
    $('.logo').remove();
    $('#clip_btn').remove();
    $('#zoomout_btn').remove();
    $('#search_box').remove();
    $('#de-header').css('min-height','0px');
    $('#de-navbar').addClass('navbakground');
    $('#de-navbar').css({'height':'35px','position':'absolute','z-index':'12','margin-bottom':'5px','display':'block'});
    if(deconf.emulator_demo) {$('#de-top-ad').css('left','210px')}
    setTimeout(function(){$('#de-navbar').css('top',navbar_top+'px')},1000);
}

    $pageContainer = $('#de-page-container');
    winHeight = $(window).height();
    winWidth = $(window).width();

	//bind page change
	$(window)

        .bind(deEvents.pageChange, function(){
           if (deconf.showDual && de.mode!='dual'){
            window.location.hash = "dual/"+de.page+"/"+de.zoom;
            return;
          }else if (!deconf.showDual && de.mode!='page') {
              window.location.hash = "page/"+de.page+"/"+de.zoom;
                return;
          }
          changePage();
          showHideAds();
        })
	//bind page render
	.bind(deEvents.renderPage, adjustInterface)
	.bind(deEvents.renderPage, preloadPage)
        .bind(deEvents.renderPage, loadPlugins)
        .bind(deEvents.renderPage, checkCookies)
        //.bind(deEvents.renderPage, autoloadChunks)
	.bind(deEvents.levelReady, showPreClipped)
	.bind(deEvents.dragFinish, onDragFinish)
	.bind(deEvents.clipFinish, onClipFinish)
	.bind(deEvents.pageDataLoaded, function(){
	  //remove loader from pagenum navbutton
	  $('.btn.pagenum .loader').remove();
          showCommentCount();
	})
        .bind(deEvents.showLoginBox, showLoginForm)
        .bind(deEvents.autoScroll,autoScroll);
      

    if (deconf.showpdf){
        $(window).bind(deEvents.renderPage,changepdf);
    }
        if(Modernizr.touch) {
            var isTap = false;
            $pageContainer
                .unbind('mousedown')
                .unbind('mouseup')
                .unbind('click')
                .unbind('mousemove')
                .unbind('mouseleave')
                .bind('touchstart',function() {isTap = true; })
                .bind('touchmove',function() {isTap = false;})
                .bind('touchend',function( evt) {if(isTap) {onTap(evt);}});

                $('#prev-page-link').click(function() {prevPage();});
                $('#next-page-link').click(function() {nextPage();});
                if(!deconf.emulator_demo) {
                    $('#de-page-container').touchwipe ({
                         wipeLeft: function() {if(de.zoom == 1) nextPage();},
                         wipeRight: function() {if(de.zoom == 1) prevPage();},
                         min_move_x: touch_dist_x,
                         min_move_y: touch_dist_y,
                         preventDefaultEvents: false
                    });
                }
               
        } else {
	 $pageContainer.bind('mousedown', onMouseDown)
	.bind('mouseup', onMouseUp)
	.bind('click', onPageClick);
        }

	$(window).scroll(onPageScroll);


  $(window).bind(deEvents.pageChange, function(){
    if( typeof(piwikTracker) != 'undefined'){
	      piwikTracker.setDocumentTitle('page '+ de.page);
        piwikTracker.trackPageView();
	  }
  });

  //update navbar page count button
  $(window).bind(deEvents.pageChange, function(){
      if (isSingleView()){
            $('#de-navbar .btn.pagenum .label').text('Page '+ de.page +' of '+ deconf.numPages);
        }else{
            $('#de-navbar .btn.pagenum .label').text('Page '+ de.page + '-' + (Number(de.page)+1) +' of '+ deconf.numPages);
        }
        removeAutoHideElements();
  })
  .bind(deEvents.renderPage, function(){
    //update zoom button's class
    if(typeof(pageData[de.page].levels.level2) == 'undefined'){
      de.zooms = '2';
    }
    $('#de-navbar .btn.zoomin').removeClass('zoomin21 zoomin22 zoomin31 zoomin32 zoomin33')
    .addClass('zoomin'+de.zooms+de.zoom.toString());

    if (de.zoom > 1){
    //    DE.unregisterPageNavigationKey();
    }else{
    //    DE.unregisterPageNavigationKey();
    }
  });

  $(window).resize(function(evt){
    $('#de-navbar').removeClass('fixed').css('left','').css('margin-left','');
    navBarOffset = undefined;
  });

    $(".autoclose").live('mouseleave',function(){
        var obj = $(this);
        setTimeout(removeAutoHideElements(),500);
    });

    $("#de-comments-btn").click(showComments);
    $('#de-footer .feedback').unbind('click').click(showFeedback);

  $('#titles-select').change(changeTitle);

  $("#de-footer-handler")
    .bind('mousedown',function(e){
      footerResizing = true;
      resetFooter = true;
      e.preventDefault();
    })
    .bind('mouseup',function(e){
        footerResizing = false;
        e.preventDefault();
    })
    .bind('click',function(){
        if (resetFooter){
            $("#de-footer").height(45);
        }
    });
  $(document)
    .bind('mouseup',function(e){ 
        footerResizing = false;
    })
      .bind('mousemove',function(e){
         if (footerResizing){
             resetFooter = false;
            var footerHeight = $(window).height() - e.clientY;
            if (footerHeight<=9) return;
            $("#de-footer").height(footerHeight);
        }
      });
  
  $("#de-navbar .btn.login").click(showSignIn);
  $("#de-user .btn.login").click(showSignIn);
  
  de.prepareForClipping = prepareForClipping;
	de.cancelClipping = cancelClipping;
	de.pageData = getPageData;
        de.drawAugmentedBox = drawAugmentedBox;
        de.getLevel = getLevel;
        de.openSubscribe = openSubscribe;
	//bind the pathchange event
	//this should be last
	$.pathchange.init();
	$(window).pathchange(checkUrl).trigger('pathchange');

	
	if ($('html').hasClass('ie8')){
	    $("a").live('click',function(e){	        
	        var link = $(this).attr('href');
	        window.location.href=link;
	        e.preventDefault();
	        return false;
	    });
	}
        if(Modernizr.touch) {
            $(window).bind('orientationchange', function(event) {
                     pageOffset =  $('#de-chunks-container').offset();
                     var move_left = (de.zoom == 1) ? pageOffset.left : $(window).scrollLeft();
                     $('#de-navbar').css({'top':(($(window).scrollTop()+navbar_top)+'px'),'left':move_left+'px'});
                     if (window.orientation == 90 || window.orientation == -90 || window.orientation == 270) {
                            if(screen_width >= 600 ) {
                                    $('#de-top-ad').css({'left':((screen.height/2)-364)+'px'});
                            } else {
                                $('#caldr_btn').show();
                                $('#subscribe_btn').show();
                                $('.prevpage').hide();
                                $('.nextpage').hide();
                            }
                      } else { 
                            if(screen_width >= 600 ) {
                                $('#de-top-ad').css({'left':((screen_width/2)-364)+'px'});
                            } else {
                                $('#caldr_btn').hide();
                                $('#subscribe_btn').hide();
                                $('.prevpage').show();
                                $('.nextpage').show();
                            }
                      }
                   
                 
            }).trigger('orientationchange');
        }
        if(deconf.emulator_demo) {$('#de-top-ad').css('left','150px');$('#de-nav-bar').css('left','150px')}
        
}

$(document).ready(function(){
    if(deconf.needsAuth && !deconf.isAuth){
        $('#de-footer .feedback').unbind('click').click(showFeedback);
        showSigninPage();
        return;            
    }
    
    if (deconf.enableLogin){
        checkLogin();
    }else{
        $(".btn.subscribe").css('visibility','visible');
        $("#de-user").hide();
    }
        
    documentReady();
    
});

$(window).unload(function(){
    //setCookies('de',(($("#de-sidebar-wrapper").css('display')=='none') ? 'false' : 'true')+','+deconf.isautoScroll.toString(),30);
});
de.isBrowserUnsupported = isBrowserUnsupported;
window.DE = de;
})(window);

