$.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load',function(){
      if (--len <= 0 && this.src !== blank){ callback.call(elems,this); }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }
  });

  return this;
};

var documentHtml = function(html){
	// Prepare
	var result = String(html)
	.replace(/<\!DOCTYPE[^>]*>/i, '')
	.replace(/<(html|head|body|title|meta|script)/gi,'<div html_tag="$1"')
	.replace(/<\/(html|head|body|title|meta|script)/gi,'</div')
	;
	
	// Return
	return result;
};

function video(movie, title, containerId, width, height, autoPlay) {
	var swfVersionStr = "10.0.0";
	<!-- xiSwfUrlStr can be used to define an express installer SWF. -->
	var xiSwfUrlStr = "";
	var flashvars = {
		movie:movie,
		title:title,
		autoPlay:autoPlay===true ? "true" : "false"
	};
	var params = {};
	params.quality = "high";
	params.bgcolor = "#000000";
	params.play = "true";
	params.loop = "true";
	params.wmode = "opaque";
	params.scale = "noscale";
	params.menu = "true";
	params.devicefont = "false";
	params.salign = "";
	params.allowscriptaccess = "sameDomain";
	params.allowfullscreen = "true";
	var attributes = {};
	attributes.id = "Player";
	attributes.name = "Player";
	attributes.align = "middle";
	$('#'+containerId).html('');
	$('#'+containerId).append('<span id="'+containerId+'_container____"></span>');
	$('#'+containerId+"_title").html(title);
	swfobject.embedSWF(
		window.STATIC_URL+"js/Player.swf?v=1", containerId+'_container____',
		width, height,
		swfVersionStr, xiSwfUrlStr,
		flashvars, params, attributes);
}

$(function(){
	$('.videobox').click(function(){
		var jthis = $(this);
		video(this.href, this.title, jthis.attr("target"), jthis.attr("width"), jthis.attr("height"), jthis.attr("autoplay") && true);
		return false;
	});
});

function setFancy() {
	$.fancybox.init();
	$('a.fancybox').fancybox({titlePosition:'inside'});
}

(function(window,undefined){

    // Prepare
    var History = window.History; // Note: We are using a capital H instead of a lower h
    if ( !History.enabled ) {
         // History.js is disabled for this browser.
         // This is because we can optionally choose to support HTML4 browsers or not.
        return false;
    }
    
    //var lastNumSlashes = History.getState().url.split(/\//g).length - 1;
    // Bind to StateChange Event
    History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
    	
    	$('#loading').show();
    	
    	$.fancybox.close();
    	
        var State = History.getState(); // Note: We are using History.getState() instead of event.state
        //History.log(State.data, State.title, State.url);
        
        if (!window.currentLanguage) {
        	window.currentLanguage = $('html').attr('lang');
        }
        
        var url = State.url.indexOf('/')!=0 ? State.url.substring(window.BASE_URL.length-1) : State.url;
        //alert(window.currentLanguage);
        //alert(url+" "+State.url);
        /*if (!State.data.changingLanguage && url.length>3 && !url.indexOf("/"+window.currentLanguage+"/")==0) {
        	
        	url = url.replace(/^\/[a-z]{2}\//,'/'+window.currentLanguage+'/');
        	if (!url.indexOf("/"+window.currentLanguage+"/")==0) {
        		url = '/'+window.currentLanguage+url;
        	}
        	History.replaceState({changingLanguage:false}, null, window.BASE_URL.substring(window.BASE_URL.length -1) + url);
        	return;
        	
        } else if (State.data.changingLanguage && url.length >= 4) {
        	var targetLanguage = url.substr(1,2);
        	if (targetLanguage != window.currentLanguage) {
        		window.currentLanguage = window.currentLanguage == 'es' ? "en" : "es";
	        	History.replaceState({changingLanguage:false}, null, State.url);
	        	window.changingLanguage = true;
	        	return;
        	}
        }*/
        
        var origin = State.data.origin;
        var destination = State.data.destination;
        if (origin == 'body') {
        	origin = '[html_tag="body"]';
        }
        
        $.ajax({
        	url:State.url,
        	type:"get",
        	error:function(jqXHR, textStatus, errorThrown){
        		$('#loading').hide();
        	},
        	success:function(data){
        		
        		
        		
            	$('#loading').hide();
        		var doc = $("<div>"+documentHtml(data)+"</div>");
        		
        		var jorigin = doc.find(origin);
        		
        		var jdestination = $(destination);
        		jdestination.html(jorigin.html());
        		
        		if (destination == 'body') {
        			jdestination.attr("class", jorigin.attr("class"));
        		}
        		/*
        		var newContent = doc.find(origin);
        		
        		newContent.css({
        			'position':'absolute',
        			'left':document.body.offsetWidth+"px",
        			'opacity':0
        		});
        		var oldContent =$(destination);
        		oldContent.css({
        			'position':'absolute'
        		});
        		$(destination).append(newContent);
        		
        		numSlashes = State.url.split(/\//g).length - 1;
        		
        		if (numSlashes>lastNumSlashes) {
        			// Moving forward
            		oldContent.animate({left:'-'+document.body.offsetWidth+"px",opacity:0},500,function(){oldContent.remove();});
            		newContent.animate({left:"0px",opacity:1},500);
        		} else if (numSlashes<lastNumSlashes) {
        			// Moving backward
        			newContent.css({
            			'left':'-'+document.body.offsetWidth+"px"
            		});
            		oldContent.animate({left:document.body.offsetWidth+"px",opacity:0},500,function(){oldContent.remove();});
            		newContent.animate({left:"0px",opacity:1},500);
            		
            		historyPosition = State.data.historyPosition;
            	} else {
            		if (window.changingLanguage) {
	            		if (State.url.indexOf("/en/")!=-1) {
		            		// Changing language
		            		newContent.css({
		            			'top':"635px",
		            			left:0
		            		});
		            		oldContent.animate({top:"-635px",opacity:0},500,function(){oldContent.remove();});
	            		//} else if (State.url.indexOf("/es/")!=-1) {
	            		} else {
	            			newContent.css({
		            			'top':"-635px",
		            			left:0
		            		});
	                		oldContent.animate({top:"635px",opacity:0},500,function(){oldContent.remove();});
	            		}
	            		newContent.animate({top:"0px",opacity:1},500);
            		} else {
	            		newContent.css({
	            			'top':"0",
	            			left:0
	            		});
	            		oldContent.delay(150).animate({opacity:0},300,function(){oldContent.remove();});
	            		newContent.animate({opacity:1},300);
            		}
            	}
            	
        		lastNumSlashes = numSlashes;
        		
            	*/
        		
        		setFancy();
        		
        		window.changingLanguage = false;
        		
        		jorigin.find('[html_tag="script"]').each(function(){
        			eval($(this).html());
        		});
        		jdestination.find('[html_tag="script"]').remove();
        		
        		
        		$('title').html(doc.find('div[html_tag="title"]').html());
        		$('html').attr('lang',doc.find('div[html_tag="html"]').attr('lang'));
        		window.currentLanguage = doc.find('div[html_tag="html"]').attr('lang');
        		
        		pageTracker._trackPageview(State.url);
    		
        	}
        });
    });

    // Change our States
    /*
    History.pushState({state:1}, "State 1", "?state=1"); // logs {state:1}, "State 1", "?state=1"
    History.pushState({state:2}, "State 2", "?state=2"); // logs {state:2}, "State 2", "?state=2"
    History.replaceState({state:3}, "State 3", "?state=3"); // logs {state:3}, "State 3", "?state=3"
    History.pushState(null, null, "?state=4"); // logs {}, '', "?state=4"
    History.back(); // logs {state:3}, "State 3", "?state=3"
    History.back(); // logs {state:1}, "State 1", "?state=1"
    History.back(); // logs {}, "Home Page", "?"
    History.go(2); // logs {state:3}, "State 3", "?state=3"
    */

})(window);

var jwindow = $(window);

$(function(){
	if (!$.browser.msie) {
		$('a').live('click',function(){
			this.blur();
			if ($(this).hasClass("fancybox")) {
				return;
			}
			if ($(this).hasClass('disabled')) {
				return;
			}
			var href =  $(this).attr("href");
			if (!href) {
				return;
			}
			if (href.indexOf("javascript")!=-1) {
				return;
			}
			if (href == History.getState().url || window.BASE_URL.substr(0,window.BASE_URL.length -1) + href == History.getState().url ) {
				return false;
			}
			
			var DEFAULT = 'body'
			
			var destination = $(this).attr("destination");
			if (!destination) {
				destination = DEFAULT;
			}
			
			var origin = $(this).attr("origin");
			if (!origin) {
				origin = DEFAULT;
			}
			
			if ($(this).hasClass("hreplace")) {
				//History.replaceState({changingLanguage:true}, null, this.href);
				History.replaceState({changingLanguage:true,origin:origin,destination:destination}, null, href);
			} else {
				History.pushState({changingLanguage:false,origin:origin,destination:destination}, null, href);
			}
			return false;
		});
	}
	$('#content').css('opacity',0);
	setFancy();
});

$(window).load(function(){
	$('#content').animate({'opacity':1},2000);
})



var scrollGaleries = function(delta){
	var galleries = $('.galleries')[0];
	if (!galleries.initialized) {
		galleries.delta = 0;
		galleries.lastDelta = -10000;
		galleries.initialized = true;
	}
	galleries.delta -= delta*3;
	if (galleries.delta < 0) {
		galleries.delta = 0;
	}
	if (galleries.delta*44 > (galleries.scrollHeight - 132)) {
		galleries.delta = Math.floor( (galleries.scrollHeight - 132) / 44 );
	}
	if (galleries.delta!=galleries.lastDelta) {
		$(galleries).stop().animate({scrollTop:galleries.delta*44},500);
		galleries.lastDelta = galleries.delta;
	}
} 

$(function(){
	$('.galleries').live('mousewheel',function(e,delta){
		scrollGaleries(delta);
	});
});


function equalHeights(a,b, offset, doProcess) {
	var offset = offset;
	var a = $(a);
	var b = $(b);
	var lh;
	if (!a.data('startHeight')) {
		lh = a[0].style.height;
		lh = lh ? lh : 'auto';
		a.data( 'startHeight', lh )
	}
	if (!b.data('startHeight')) {
		lh = b[0].style.height;
		lh = lh ? lh : 'auto';
		b.data( 'startHeight', lh )
	}
	a[0].style.height = a.data('startHeight');
	b[0].style.height = b.data('startHeight');
	
	if (!offset) {
		offset = 0;
	}
	var abot = a.offset().top + a.height();
	var bbot = b.offset().top + b.height();
	var dif = abot - bbot + offset;  
	if (dif<0) {
		a.height(a.height()-dif);
	} else {
		b.height(b.height()+dif);
	}
	
	
	if (doProcess) {
	} else {
		$(window).load(function(){
			equalHeights(a,b, offset, true);
		});
		$(window).load(function(){
			setTimeout(function(){
				equalHeights(a,b, offset, true);
			}, 500);
			setTimeout(function(){
				equalHeights(a,b, offset, true);
			}, 1000);
			setTimeout(function(){
				equalHeights(a,b, offset, true);
			}, 1500);
			setTimeout(function(){
				equalHeights(a,b, offset, true);
			}, 2000);
		});
		equalHeights(a,b, offset, true);
		setTimeout(function(){
			equalHeights(a,b, offset, true);
		}, 500);
		setTimeout(function(){
			equalHeights(a,b, offset, true);
		}, 1000);
	}
}
