var galleryCurrentElement = 0;

function beforeInitialize() {

  // actualizar los enlaces externos
	fix_external_links();
	

  // inicializar capas lightbox
	box = new MultiBox('mb', {descClassName: 'vacio',showControls: false, useOverlay: !iPhoneCheck()});
	
	if (($("locations")) || ($("contact"))) {
		box = new MultiBox('photos', {descClassName: 'vacio',showControls: true, useOverlay: !iPhoneCheck()});
		box = new MultiBox('photos2', {descClassName: 'vacio',showControls: true, useOverlay: !iPhoneCheck()});
	}
	
	// Montar Ajax navegación commercials
	if ($("ajax_commercial")) {
		// Cambiamos links
		$$("#ajax_commercial li a").each(function(element) {
			var commId = element.getAttribute("id").substring(4);
			element.addEvent('click', function(event) {
				event = new Event(event); event.stop();
				loadCommercial(commId);
			});
		}); 
	}
	
	// Ajax rollovers
	if (($("gallery")) && (!($("contact")))) {
		$$("#gallery ul li").each(function(element) {
			var liId = element.getAttribute("id");
			if ((($$("#gallery ul"))[0]).hasClass("directors")) {
				element.addEvent('click', function() { box.open($("a_" + liId)); })
			}
			if ( ((($$("#gallery ul"))[0]).hasClass("commercials")) || ((($$("#gallery ul"))[0]).hasClass("photography")) ) {
				element.addEvent('click', function() { document.location.href = "javascript:loadCommercial("+liId+")"; })
			}
			if ( ((($$("#gallery ul"))[0]).hasClass("photography")) ) {
				element.addEvent('click', function() { document.location.href = "javascript:loadPhotography("+liId+")"; })
			}
			element.addEvent('mouseover', function() {  this.addClass("over"); });
			element.addEvent('mouseout', function() { this.removeClass("over"); });
		});
	}
	
	// Montar Ajax navegación photography
	if ($("ajax_photography")) {
		// Cambiamos links
		$$("#ajax_photography li a").each(function(element) {
			var commId = element.getAttribute("id").substring(4);
			element.addEvent('click', function(event) {
				event = new Event(event); event.stop();
				loadPhotography(commId);
			});
		});
	}
}

function loadCommercial(param) {
	$("gallery").setStyle("display", "none");
	var url = JS_URL + "ajax/get-commercial/" + param;
	    var myAjax = new Ajax(url, {method: 'get', 
	                                update : 'ajax_tab', 
																	evalScripts : true,
	                                onComplete : showCommercial
	    }).request();
}

function showCommercial() {
	$("ajax_tab").setStyles({"opacity" : "0", "display" : "block"});
	$('content-list').setStyle('height', $('ajax_tab').getSize().size.y);
	setTimeout("$('content-list').setStyle('height', $('ajax_tab').getSize().size.y);", 200);
	var fx_tab = $("ajax_tab").effects({duration: 500, transition: Fx.Transitions.Quint.easeOut});
	fx_tab.start({"opacity" : 1});
	$("a_back").setStyle("display", "block");
}

function closeTab() {
	if ($("ajax_tab")) {
		var fx_tab = $("ajax_tab").effects({duration: 500, transition: Fx.Transitions.Quint.easeOut});
		fx_tab.start({"opacity" : 0}).chain(function() { $("ajax_tab").setStyle("display", "none"); });
	}
	$("a_back").setStyle("display", "none");
	if ($("ficha")) $("ficha").setHTML("");
	if ($("description")) $("description").setStyle("display", "block");
	$("gallery").setStyle("display", "block");
	if ($("gallery_2")) $("gallery_2").setStyle("display", "none");
	
	if ($("titulo_ficha")) $("titulo_ficha").innerHTML = "";
	if (selectedElement != null) {
		var myFx = new Fx.Scroll(window).toElement($$("li#"+ selectedElement)[0]);
		selectedElement = null;
	}
}


var selectedElement = null;
function loadPhotography(param) {

  $("gallery").setStyle("display", "none");

	// Cambio perfil
	var url = JS_URL + "ajax/get-photo-profile/" + param;
	    var myAjax = new Ajax(url, { method: 'get', 
	                                 update : 'ficha'
	    }).request();

	// Cambio galería
	
	var url = JS_URL + "ajax/get-photo-gallery/" + param;
			    var myAjax = new Ajax(url, {method: 'get', 
			                                update : 'gallery_2', 
			                                onComplete : showPhotography
			    }).request();
	
	// Cambio titulares
	var url = JS_URL + "ajax/get-photo-titles/" + param;
			    var myAjax = new Ajax(url, {method: 'get', 
			                                update : 'titulo_ficha',
																		  onComplete : function() { $("description").setStyle("display", "none"); }
			    }).request();

	var myFx = new Fx.Scroll(window).toTop();
	selectedElement = param;
	
}

function showPhotography() {
	$("a_back").setStyle("display", "block");
	$("gallery_2").setStyle("display" , "block");
	box = new MultiBox('photos', {descClassName: 'vacio',showControls: true, useOverlay: !iPhoneCheck()});
}




function initialize(){
	// Iguala las alturas de los lis (de 3 en 3)
	if ($$("ul.sameHeightList").length > 0) {
		var count = 1;
		var maxHeight = 0;
		var arrElements = new Array();
		$$("ul.sameHeightList li").each(function(element){

			if ($(element).getStyle("height").toInt() > maxHeight) maxHeight = $(element).getStyle("height").toInt();
			arrElements.push(element);

			if (count++==3) { 
				// Alineamos todos los elementos a la altura mayor
				for (var ii = 0; ii < arrElements.length; ii++) {
					$(arrElements[ii]).setStyle("height", maxHeight);
				}
				arrElements = new Array();
				maxHeight = 0;
				count = 1; 
			}
			
		});
		// Alineamos todos los elementos a la altura mayor
		for (var ii = 0; ii < arrElements.length; ii++) {
			$(arrElements[ii]).setStyle("height", maxHeight);
		}
	}
		
}

function number_format(numero){
   rtnValue = format_number(numero, 2, '.',',');
   
   return rtnValue;
}

function format_number( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

// cambia los enlaces con rel external por _blank
function fix_external_links() { 
    $ES('a').each(function(el) { 
        if (el.getProperty('rel') == 'external') { 
            el.addEvent('click', function(e) { 
                e = new Event(e); 
                e.stop();     
                window.open(this.getProperty('href')); 
            }.bind(el)); 
        }     
    }); 
} 

window.addEvent("domready", function() { beforeInitialize()});
window.addEvent("load", function() {initialize()});

function iPhoneCheck() {
  var agent = navigator.userAgent.toLowerCase();
  var iphone = (agent.indexOf('iphone')!=-1);
  if (iphone) {
     return true;
  } else {
     return false;
  }
}


      
var box = {};

// CSS Browser Selector   v0.2.5
// Documentation:         http://rafael.adm.br/css_browser_selector
// License:               http://creativecommons.org/licenses/by/2.5/
// Author:                Rafael Lima (http://rafael.adm.br)
// Contributors:          http://rafael.adm.br/css_browser_selector#contributors
var css_browser_selector = function() {
	var ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();
