var type = "IE"; // Variable used to hold the browser name

detectBrowser();

function detectBrowser() {
  if (window.opera && document.readyState) {
    type="OP"; // The surfer is using Opera of some version
  } else if (document.all) {
    type="IE"; // The surfer is using IE 4+
  } else if (document.layers) {
    type="NN"; // The surfer is using NS 4
  } else if (!document.all && document.getElementById) {
    type="MO"; // The surfer is using NS6+ or Firefox
  } else {
    type="IE"; // I assume it will not get here
  }
}

document.onkeydown = function(e) {
  if (!e) {
    // If the browser did not pass the event information to the
    // function, we will have to obtain it from the event register.
    if(window.event) {
      e = window.event; // IE 4+
    } else {
      return;
    }
  }
  if (typeof(e.keyCode) == 'number') {
    e = e.keyCode;  // DOM
  } else if (typeof(e.which) == 'number') {
    e = e.which;    // NS 4
  } else if(typeof(e.charCode) == 'number') {
    e = e.charCode; // NS 6+, Mozilla 0.9+
  } else {
    return;
  }
  if ((e==39 || e==63235) && document.getElementById("next")) {
    location.href = document.getElementById("next").href;
  } else if ((e==37 || e==63234) && document.getElementById("prev")) {
    location.href = document.getElementById("prev").href;
  }
}

/*****************************************************************************/

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

/*****************************************************************************/

var leftmost = -190;
var rightmost = 10;
var interval = null;
var sidebarVisible = false;
var DOMCapable;

document.getElementById ? DOMCapable=true : DOMCapable=false;

function scrollRight(menuId) {
  var leftPosition;
  if (DOMCapable) {
    leftPosition = parseInt(document.getElementById(menuId).style.left);
    if (leftPosition >= rightmost) {
      clearInterval(interval);
      return;
    } else {
      leftPosition += 10;
      document.getElementById(menuId).style.left = leftPosition+"px";
    }
  }
}

function scrollLeft(menuId) {
  if (DOMCapable) {
    leftPosition = parseInt(document.getElementById(menuId).style.left);
    if (leftPosition <= leftmost) {
      clearInterval(interval);
      return;
    } else {
      leftPosition -= 10;
      document.getElementById(menuId).style.left = leftPosition+"px";
    }
  }
}

function slideIn(menuId) {
  if (document.getElementById(menuId)) {
    clearInterval(interval);
    interval = setInterval('scrollRight("'+menuId+'")', 5);
  }
  sidebarVisible = true;
}

function slideOut(menuId) {
  if (document.getElementById(menuId)) {
    clearInterval(interval);
    interval = setInterval('scrollLeft("'+menuId+'")', 5);
  }
  sidebarVisible = false;
}

function toggleSidebar(menuId) {
  if (!sidebarVisible) {
    slideIn(menuId);
  } else {
    slideOut(menuId);
  }
}

/*****************************************************************************/

function popImage(img, title) {
  picfile = new Image();
  picfile.src = img;
  picfile.imageTitle = title;
  fileCheck(100);
}

function fileCheck(i) {
  if ((picfile.width != 0 && picfile.height != 0) || i == 0) {
    makeWindow();
  } else {
    setTimeout("fileCheck(" + (i-1) + ")", 50);
  }
}

function makeWindow() {
  var img = picfile.src, wd = picfile.width, ht = picfile.height, title = picfile.imageTitle;
  var args = "resizable=yes";
  if (wd == 0) {
    // Default window size if image load is slow
    wd = 800;
    ht = 600;
    args += ",scrollbars=yes";
  }

  if (window.screen) {
    var isIE = (navigator.appName.indexOf("Microsoft") != -1) ? 1 : 0;
    var avwd = screen.availWidth, avht = screen.availHeight;

    if (avwd < wd || avht < ht) { args += ",scrollbars=yes"; }

    var xcen = (avwd > wd) ? (avwd - wd) / 2 : 0;
    var ycen = (avht > ht) ? (avht - ht) / 2 : 0;
    args += ",left=" + xcen + ",screenX=" + xcen;
    args += ",top=" + ycen + ",screenY=" + ycen;

    if (avwd < wd) {
      wd = avwd;
      if (isIE) wd -= 12;
    }
    if (avht < ht) {
      ht = avht;
      if (isIE) ht -= 32;
    }
  }
  args += ",width=" + wd + ",innerWidth=" + wd;
  args += ",height=" + ht + ",innerHeight=" + ht;

  popwin = window.open(img, 'fullSize', args);
  popwin.document.open();
  popwin.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
  popwin.document.write('<html>');
  popwin.document.write('<head>');
  popwin.document.write('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>');
  popwin.document.write('<title>'+title+'</title>');
  popwin.document.write('</head>');
  popwin.document.write('<body style="margin:0px"><a href="javascript:window.close()"><img src="'+img+'" border="0" alt="'+title+'"/></a></body>');
  popwin.document.write('</html>');
  popwin.document.close();
}

/*****************************************************************************/

var exifVisible = false;

function setLayer(obj,lyr) {
  var newX = findPosX(obj)+5;
  var newY = findPosY(obj)+5;
  var x = new getObj(lyr);
  x.style.top = newY + 'px';
  x.style.left = newX + 'px';
}

function findPosX(obj) {
  var curleft = 0;

  if (!obj) { return curleft; }
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  } else if (obj.x) {
    curleft += obj.x;
  }
  return curleft;
}

function findPosY(obj) {
  var curtop = 0;

  if (!obj) { return curtop; }
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  } else if (obj.y) {
    curtop += obj.y;
  }
  return curtop;
}

function getObj(id) {
  if (type=="IE") {
    this.obj = document.all[id];
    this.style = document.all[id].style;
  } else if (type=="MO" || type=="OP") {
    this.obj = document.getElementById(id);
    this.style = document.getElementById(id).style;
  } else if (type=="NN") {
    if (document.layers[id]) {
      this.obj = document.layers[id];
      this.style = document.layers[id];
    }
  }
}

function toggleExif(parentId, id) {
  var parent = document.getElementById(parentId);

  MM_showHideLayers(id,'',(exifVisible) ? 'hide' : 'show');
  setLayer(parent,id);

  exifVisible = !exifVisible;
}

function getTagContent(html, tag, debug) {
    if (html==null || html == '') return '';
    if (tag==null || tag == '') tag = 'body';
    if (debug==null || debug!=true) debug = false;
    start_tag = '<!--'+tag+':start-->';
    stop_tag = '<!--'+tag+':stop-->';
    start = html.indexOf(start_tag) + start_tag.length; // l'inizio privo della stringa stessa
    stop = html.indexOf(stop_tag);
    content = html.substring(start,stop);
    // debug mode
    if (debug) {
        content = content.
	replace( /&(?!#?\w+;)/g , '&amp;'    ).
	replace( /</g           , '&lt;'     ).
	replace( />/g           , '&gt;'     ).
	replace( /"/g           , '&ldquo;'  ).
	replace( /"/g           , '&rdquo;'  );
    }
    return content;
}

function reloadPageAfterClick(html) {
    main_html = getTagContent(html, 'main_content');
    $('#gsBody').html(main_html);
}

function ajaxError(XMLHttpRequest, textStatus, errorThrown) {
  // typically only one of textStatus or errorThrown 
  
  // handle various error type
  var status = 200; // Request OK
  try {
    status = XMLHttpRequest.status;
  }
  catch(e) {
    // handle no status  
  }
  alert(errors);
}

function ajaxClick(object) {
    var action = $(object).attr('href');
    $.ajax({
            url: action,
            cache: false,
            error: ajaxError,
            success: function(html){
                reloadPageAfterClick(html);
                reloadAll();
                return false;
            }
    });
    return false;
}

function disableButtonElement(options) {
    //$(options.object).css('visibility', 'hidden');
    $(options.object).css('opacity', '.2');
}

function enableButtonElement(options) {
    //$(options.object).css('visibility', 'visible');
    $(options.object).css('opacity', '1.0');
}

function hideElement(options) {
    //$(options.ohide).hide();
}


/***********************************( Init JQuery functions )******************************************/
function reloadAll() {

  try {
    // give tooltip and right menu for actions on items
    // apply alpha if possible
    $().bt.defaults.fill = 'rgba(68, 68, 68, 0.4)';
    $(".giAlbumCell, .giItemCell, .giMovieCell, .giMicroThumbCell").each(function () {
      if($(this).find('ul').length > 0) {
        var id = $(this).find('ul').attr('id');
        if(id) {
          $(this).find('a').contextMenu({
            menu: id
          },
          function(href, onclick, action, el, pos) {
            if(onclick) return false; // break code
            window.location=href;
                  /*alert(
                          'Action: ' + action + '\n\n' +
                          'Element click: ' + $(el).parent().html() + '\n\n' + 
                          'X: ' + pos.x + '  Y: ' + pos.y + ' (relative to element)\n\n' + 
                          'X: ' + pos.docX + '  Y: ' + pos.docY+ ' (relative to document)'
                          );*/
          });
        }
      }
      
      // create tooltip
      var content = '<span class="_popup">'+$(this).find('.popup').html()+'</span>';
      if($(this).hasClass('giMovieCell')) {
        $(this).find('.itemLink a').bt(content, {
          trigger: 'hover',
          positions: 'top',
          padding: 5,
          spikeGirth: 10,
          spikeLength: 10,
          width: 180,
          cornerRadius: 15,
          fill: 'rgba(68, 68, 68, 0.8)',
          cssStyles: {left:0, width:'auto'}
        })
      }
      else {
        $(this).find('.itemLink a').bt(content, {
          trigger: 'hover',
          positions: 'top',
          padding: 5,
          spikeGirth: 10,
          spikeLength: 10,
          width: 180,
          cornerRadius: 15,
          cssStyles: {left:0, width:'auto'}
        })
      }
    });
    
    // info about thumb flying popup
    $('.vSlider .giMicroThumbCell img').bt({
        trigger: 'hover',
        positions: 'top',
        padding: 10,
        spikeGirth: 10,
        spikeLength: 10,
        width: 180,
        cssStyles: {color:'#FFFFFF', width:'auto', marginLeft:60, fontFamily:'sans-serif', fontWeight:100, fontSize: 12, left:0},
        cornerRadius: 15
      });
    
    try {
      $(".hSlider").elementSlider({
        disableButtonCallback: disableButtonElement,
        enableButtonCallback: enableButtonElement
      });
    }catch(e) {
      alert(e);
    }
    try {
      $(".vSlider").elementSlider({
        viewable: 5,
        displayCallback: displayVElement,
        disableButtonCallback: disableButtonElement,
        enableButtonCallback: enableButtonElement,
        nextButton: $('.vdown'),
        prevButton: $('.vup')
      });
    }catch(e) {alert(e);}
    
  } catch(e) {
    // Errors
    //alert(e);
  }
  
  //$(".hSlider a").click(function() {
  //  return ajaxClick(this);
  //});
  //// font swf
  //try {
  //  // fonts loading
  //  if(typeof sIFR == "function"){
  //    // personal page
  //    sIFR.replaceElement("#personalized h1", baseurl+'fonts/truetypes/FuturaLightBT.swf', named({
  //      sColor: "#FFFFFF",
  //      sWmode: 'transparent'
  //    }));
  //    sIFR.replaceElement("#personalized p", baseurl+'fonts/truetypes/FuturaLightBT.swf', named({
  //      sColor: "#666666",
  //      sWmode: 'transparent'
  //    }));
  //    
  //    // others (photo)
  //    sIFR.replaceElement(".smalltitle", baseurl+'fonts/truetypes/FuturaLightBT.swf', named({
  //      sColor: "#FFFFFF",
  //      sWmode: 'transparent'
  //    }));
  //    
  //    //sIFR.replaceElement(".smalltitle", baseurl+'fonts/truetypes/Dreamspeak.swf', named({
  //    //  sColor: "#FFFFFF",
  //    //  sWmode: 'transparent',
  //    //  sFlashVars: 'offsetTop=5'
  //    //}));
  //    sIFR.replaceElement(".gsContentDetail .giInfo", baseurl+'fonts/truetypes/FuturaLightBT.swf', named({
  //      sColor: "#FFFFFF",
  //      sWmode: 'transparent'
  //    }));
  //    sIFR.replaceElement(".gsContentDetail .giDescription", baseurl+'fonts/truetypes/FuturaLightBT.swf', named({
  //      sColor: "#666666",
  //      sLinkColor: "#FFFFFF",
  //      sWmode: 'transparent'
  //    }));
  //    sIFR.replaceElement(".gsContentMovies th", baseurl+'fonts/truetypes/FuturaLightBT.swf', named({
  //      sColor: "#666666",
  //      sWmode: 'transparent'
  //    }));
  //    
  //  }
  //} catch(e) {
  //  //alert(e);
  //}
  
  // preload images
  //$('.hSlider img').preload({
  //    placeholder:true,
  //    find:/\.(jpg)/,
  //    threshold: 2
  //});
  
  /**
    * All the functions below, are used to update the summary div
    * That is not the objective of the plugin, the really important part 
    * is the one right below. The option placeholder, and threshold.
    */
   $.preload( '.hSlider img', {//the first argument is a selector to the images
           placeholder:baseurl+'images/img-loader.gif',//this is the really important option
           notFound:baseurl+'images/8fx.png',//optional image if an image wasn't found
           threshold: 2 //'2' is the default, how many at a time, to load.
   });
   
   $.preload( '.vSlider img', {//the first argument is a selector to the images
           placeholder:baseurl+'images/img-loader.gif',//this is the really important option
           notFound:baseurl+'images/8fx.png',//optional image if an image wasn't found
           threshold: 2 //'2' is the default, how many at a time, to load.
   }); 
    
   //$.preload( '.hSlider img', {//the first argument is a selector to the images
   //        onRequest:request,
   //        onComplete:complete,
   //        onFinish:finish,
   //        placeholder:baseurl+'images/img-loader.gif',//this is the really important option
   //        notFound:baseurl+'images/8fx.png',//optional image if an image wasn't found
   //        threshold: 2 //'2' is the default, how many at a time, to load.
   //});
   
   //function update( data ){
   //        $('#done').html( ''+data.done );
   //        $('#total').html( ''+data.total );
   //        $('#loaded').html( ''+data.loaded );
   //        $('#failed').html( ''+data.failed );
   //};
   //function complete( data ){
   //        update( data );
   //        $('#image-next').html( 'none' );//reset the "loading: xxxx"
   //        $('#image-loaded').html( data.image );
   //};
   //function request( data ){
   //        update( data );
   //        $('#image-next').html( data.image );//set the "loading: xxxx"
   //};
   //function finish(){//hide the summary
   //        $('#summary').fadeOut('slow');
   //};
  
  // load ajax links
  $('.vSlider .giMicroThumbCell .photoThumbLink').each(function() {
    $(this).click(function() {
        var selected_item = $(this);
        var link_url = $(this).attr('href');
        // if rewrite url
        if(link_url.indexOf("?") == -1) {
            link_url += '?ajax=1';
        }
        else {
            link_url += '&ajax=1';
        }
        $('#photo img').fadeTo("slow", 0.40);
        $.ajax({
            type: "GET",
            url: link_url,
            success: function(html){
              $('#giPreview').html(html);
              activateVerticalSelection(selected_item);
              loadImage();
            }
        });
        return false;
    });
  });
  
  
  // positioning for screen resolution lower than wide screen
  if(screen.width <= 1200) {
    $('#gallery #gMainContent').css('margin', 'auto');
    $('#gallery #gMainContent').css('margin-top', '2%');
  }
  
  
  // Flip image if preview
  loadImage();

}

function activateVerticalSelection(object) {
    $(".vSlider .giMicroThumbCell").each(function() {
        if($(this).attr('id') == 'microThumbCurrent') {
            $(this).removeAttr('id');
        }
    });
    object.parent().attr('id', 'microThumbCurrent');
}

function loadImage() {
  // Flip image if preview
  if($("#photo img")) {
    var direction = 'bt';
    if($("#photo img").width() > $("#photo img").height()) {
      var direction = 'lr';
    }
    $("#photo img").flip({
        direction: direction,
        bgColor: '#000000',
        color: '#333333'
    });
    //$("#photo img").fadeIn('slow');
  } else {
    //alert('not present');
  }
}

$(document).ready( function() {

  reloadAll();
  
});