// JavaScript Document
var nPages;
var curPage;

// Browser detection
var agent=navigator.userAgent.toLowerCase();
var is_iphone = (agent.indexOf('iphone')!=-1);
var is_ie6 = jQuery.browser.msie && (jQuery.browser.version < 7);
//var is_ie7 = jQuery.browser.msie && (jQuery.browser.version > 6);

jQuery(function(){ 	
  FLIR.init( { path: '/fr/' } );
  jQuery('.flir-text,.qtrans_language_chooser a' ).each( function() { FLIR.replace(this, new FLIRStyle( {realFontHeight:true})); } );  
  jQuery('.easy-form').EasyForms();  
  jQuery('li.share ul').hide();  
  jQuery("li.share a.share-button").click(function(){jQuery('li.share ul:visible').slideUp('fast');jQuery('li.share ul:hidden').slideDown('fast');return false;});
  jQuery("input.stdinput,textarea.stdinput").focus(function(){jQuery(this).addClass("stdinput-sel");}).blur(function(){jQuery(this).removeClass("stdinput-sel");});
  jQuery(".thickbox").fancybox({
					'fancyLoading'			: true,
					'overlayShow'			: false,
					'zoomSpeedIn'			: 300,
					'zoomSpeedOut'			: 300,
					'frameWidth'			: 600,
					'frameHeight'			: 400,					
					'padding'				: 5,	
					'hideOnContentClick'	: true
  }); 
  jQuery('#wrapper div.tweets li a:last').addClass('tw-on');
  
  
  if (curPage == 1){
  // Creo gli elementi vuoti
   for (var i = curPage; i < nPages; i++) {	   
	 jQuery("#selected-works > ul").append("<li>Loading...</li>");   
	   
   }
  }
 
 
 if(!is_iphone){
 jQuery("#carousel-home").jcarousel({
        scroll: 1,
	    auto: 5,
		wrap:"last",
		animation: 500,
        initCallback: slideshow_initCallback,
		itemVisibleOutCallback: {            
            onAfterAnimation:  slideshow_itemVisibleOutCallbackAfterAnimation
        },
		itemVisibleInCallback: {         
            onAfterAnimation:  slideshow_itemVisibleInCallbackAfterAnimation
        },
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
  }); 
 }
 if(!is_iphone && curPage == 1){
  jQuery("#selected-works").jcarousel({
        scroll: 1,	    
		animation: 500,
		wrap:"last",
		size:nPages,
		offset:curPage,
		start:curPage,		
		itemLoadCallback: slideshow_itemLoadCallbackFunction,	
        initCallback: slideshow_initCallback,
		itemVisibleOutCallback: { 
            onAfterAnimation:  slideshow_itemVisibleOutCallbackAfterAnimation
        },
		itemVisibleInCallback: {         
            onAfterAnimation:  slideshow_itemVisibleInCallbackAfterAnimation
        },
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
  }

   
	 if(!is_iphone){
	// Launch video
	jQuery("li.play a,.apertura-play").click(function(){
	  var videoUrl = jQuery(this).attr('href');
	  var videoDescription = jQuery(this).attr('title');
	if( !is_ie6 ){
	jQuery("#videoplayer").show().animate({width: "80%"}, 1200,function(){loadVideo(videoUrl,videoDescription );});	 	
	}else{
	var p = $("#videoplayer");	
	var position = p.position();  
	var lunghezza =  jQuery(window).width()-220;
	p.css('height', jQuery(window).height());
	p.show().animate({width: lunghezza}, 1200,function(){loadVideo(videoUrl,videoDescription );});	 		
	}
	 
	  return false;
	});
	
	// Close video
	jQuery("#close-video").click(function(){	
	  jQuery("#video-container").html('');	
	  //swfobject.removeSWF("videoflash");
	  jQuery("#videoplayer").animate({width: "0%"},600, function(){jQuery("#videoplayer").hide(); jQuery("#blog-search").show();});	 
	  return false;
	}); 
	 }
		
	// Popup	
	jQuery('.standard-links-list a[href^="http://"],div.text-format a[href^="http://"],.launch a, a.launch').not('.nopop').click(function(){
		var siteUrl = jQuery(this).attr('href');	
		//console.log(siteUrl.slice(0,29));
		if (!(siteUrl.slice(0,29) == 'http://www.studiohangloose.it')){		
			var videoDescription = jQuery(this).attr('title');	
			var currentLocation = document.location.href;
			window.location = '/popup/?url='+URLEncode(siteUrl)+'&ref='+URLEncode(currentLocation);	 
			return false;
		}		
	});
	
	// MiniSlideShow Init
	if (totImages>0){
		jQuery('#navbar').prepend('<div id="image-faker">&nbsp;</div>');
		jQuery('#image-faker').animate({opacity: 0 }, 0).css('background-image', 'url(/backgrounds/'+curImage+'.jpg)');  
		setInterval( "slideSwitch()", 5000 );
	}
	
	
});

function loadVideo(videoUrl,videoDescription ){
	jQuery("#blog-search").hide();
	  jQuery("#video-description").html(videoDescription);
	  jQuery("#video-container").html('');	  	
		jQuery.ajax({		
			url: "/videopopup.php?v="+videoUrl,			
			dataType: "html",
			success: function(data){				
				jQuery("#video-container").html(data);			
	  			}
		});
}
// More usable Forms V 2.3  By Oliver Astrologo
jQuery.fn.EasyForms=function(){
this.submit( function() {
			var submitForm = this;
			jQuery(submitForm).find("label").not(".radiolabel").each(function(){
				var current=jQuery(this);
				var targetForm =  jQuery('#'+current.attr("for"));				
				if (targetForm.val() == current.html()){
				targetForm.val('');
				};																			  
			});
		return true;
	});	
	this.find("label").not(".radiolabel").each(function(){
		var current=jQuery(this);		
		var targetForm = jQuery('#'+current.attr("for"));	   
	   if (targetForm.val() == ''){
			targetForm.val(current.html());		
			}	   
	   targetForm.click(function(){		
		if (jQuery(this).val() == current.html()){
			jQuery(this).val('');			
			}
		});
		targetForm.blur(function(){		
		if (jQuery(this).val() == ''){
			jQuery(this).val(current.html());			
			}
		});
		current.hide();	
	});			
}

jQuery.fn.confirm_prompt = function(stringa) {
newlocation = jQuery(this).get(0);	
this.click(function() {
	 if (confirm(stringa)) {
      window.location = newlocation;
    }else{
	return false;
	}});
}

/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
function slideshow_initCallback(carousel) {
	
	
	
	
    jQuery('.paginator a').not('.slideshow-next,.slideshow-prev').bind('click', function() {
       carousel.startAuto(0);		
	   carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); 		
	 return false;
    });

    jQuery('.slideshow-next').bind('click', function() {
    jQuery(".description-tab").hide();	
	carousel.startAuto(0);
	carousel.next();	  
	 return false;
    });

    jQuery('.slideshow-prev').bind('click', function() {
		 jQuery(".description-tab").hide();
      // jQuery('.paginator a').removeClass('current');
	   carousel.prev();
	   carousel.startAuto(0);		
        return false;
    });
	
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });	
	 jQuery('.slideshow-next,.slideshow-prev').mouseover(function(){jQuery(this).addClass("hover");}).mouseout(function(){jQuery(this).removeClass("hover");});
};
/**
 * This is the callback function which receives notification
 * when an item is no longer the first one in the visible range.
 * Triggered after animation.
 */
function slideshow_itemVisibleOutCallbackAfterAnimation(carousel, item, idx, state) {
   jQuery(".jcarousel-item-"+idx+" .description-tab").hide();
};
/**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 * Triggered after animation.
 */
function slideshow_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {
 
  jQuery(".jcarousel-item-"+idx+" .description-tab").slideDown("slow");  
  jQuery('.paginator a').removeClass('current');		
  jQuery(".slideshow-button-"+(idx-1)).addClass('current');
};


function slideshow_itemLoadCallbackFunction(carousel, state)
{
    
	for (var i = carousel.first; i <= carousel.last; i++) {
     //  console.log( carousel.last);
	   // Check if the item already exists
        if (!carousel.has(i)) {
			carousel.add(i, "");
			
		}
		if (jQuery(".jcarousel-item-"+i).html() == "Loading..."){
		jQuery("#selected-works").addClass("is-loading");
		    jQuery.ajax({		
			url: '/'+enURL+'works/tile/'+(i-1)+'/ajax/',			
			dataType: "html",
			success: function(data){				
				//jQuery("#ajax-element-"+(jQuery(this).text())).html(data);
				 jQuery("#selected-works").removeClass("is-loading");	
				 jQuery(".jcarousel-item-"+(i-1)).html(data).hide().fadeIn('fast');			
	  			}			
		});	}
     }    // Add the item
      			
        
    
};
// Pre-submit callback
function showRequest(XMLHttpRequest) {
jQuery('#loading').fadeIn('fast');
}
// Post-submit callback
function showResponse(XMLHttpRequest, textStatus)  {
jQuery('#loading').fadeOut('slow');
}
// Ajax Error Catchig
function handleError(XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
jQuery('#loading').fadeOut('slow');
alert('Ops! Sembra che si sia verificato un errore durante la comunicazione con il server, prova a ricaricare la pagina.');
}
jQuery.ajaxSetup({
global: true,
type: "GET",
beforeSend:showRequest,
complete: showResponse ,
error:handleError
});

// Hangloose miniSlideSwitch
function slideSwitch() {  
  
		jQuery('#image-faker').animate({opacity: 1.0}, 1000, function() { 
			jQuery('#navbar').css('background-image', 'url(/backgrounds/'+curImage+'.jpg)'); 
			curImage++;
			if (curImage>totImages) curImage=1;	 
			jQuery('#image-faker').animate({opacity: 0 }, 0).css('background-image', 'url(/backgrounds/'+curImage+'.jpg)');	 
		 }); 
	
}

// URL Encode function
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}


