/************* Defino variables globales ****************/
gMaps = false; // Si esta cargada la libreria de gMaps, por default false
chatLoaded = false;

function gMapsLoad (fn) {

//alert('gMaps');
	if (gMaps) {
//alert(fn);
//		fn();
		return;
	}
	new Element('script', {'src': 'http://maps.google.com/maps?file=api&async=2&callback='+fn+'&v=2&key='+gMaps_API_key, 'type': 'text/javascript'}).inject($('scripts-container'), 'bottom');
	gMaps = true;	
//alert(gMaps);
}

function chatLoad () {
	if (chatLoaded) return;

	document.addEvent('load', function() {
		new Element('script', {'src': 'http://www.avantrip.com/chat/js/status_image.php?base_url=http://www.avantrip.com/chat&l=betatrip&x=1&deptid=1&text=Chat Online', 'type': 'text/javascript'}).inject($('scripts-container'), 'bottom');
		chatLoaded = true;
	});
}

function setCurrency (newCurrency) {

	// Parche por cambiar ARS a ARS $
//	if (newCurrency = 'ARS') newCurrency = 'ARS $';

	// Seteo el nuevo currency
	currencyDefault = newCurrency;

	var prices = $$('.price'), amount, newAmount, hasAmount=false, oldCurrency;
	for (var i=0; i < prices.length; i++) {
		if (prices[i].getElement('.currency')) {
			if (prices[i].getElement('.currency').getProperty('code')) {
				amount = 0;
//if (!prices[i].getElement('.currency').getProperty('code')) alert(prices[i]);

				var oldCurrency = prices[i].getElement('.currency').getProperty('code').toUpperCase();

				// Parche por cambiar ARS a ARS $
				//if (oldCurrency = 'ARS') oldCurrency = 'ARS $';
				// Cambio el simbolo del currency
				if (prices[i].getElement('.currency')) 
					prices[i].getElement('.currency').set('html', currencyTable[newCurrency].symbol);
/*
				// Cambio el codigo del currency
				if (prices[i].getElement('.currency')) 
					prices[i].getElement('.currency').setProperty('code', newCurrency);
*/					
				// Obtengo el amount de la propiedad value de la clase amount. Si no la tiene, lo tomo del texto y la seteo con ese valor
				if (prices[i].getElement('.amount').getProperty('val')) {
					amount = Math.ceil(parseFloat(prices[i].getElement('.amount').getProperty('val')));
				} else if (prices[i].getElement('.amount')) {
					amount = Math.ceil(parseFloat(prices[i].getElement('.amount').get('text')))
					prices[i].getElement('.amount').setProperty('val', amount);
				}

				// Cambio el valor del precio
				if  (amount > 0) {
					//var newAmount = Math.ceil(((currencyTable[newCurrency].conversion/currencyTable[oldCurrency].conversion)*amount));
					var newAmount = calculateAmount(amount, oldCurrency, newCurrency);
					prices[i].getElement('.amount').set('text', newAmount);
				}
			}
		}
	}

	// Disparamos un custom event "setCurrency"
	if ($('currency')) 
		$('currency').fireEvent('change');

}

function calculateAmount(amount, currencyOld, currencyNew) {
	if (!currencyNew) currencyNew = currencyDefault;
	return Math.ceil(((currencyTable[currencyNew].conversion/currencyTable[currencyOld].conversion)*amount));
}

function changeCurrency (newCurrency) {
//alert(newCurrency);
//return;

	setCurrency(newCurrency);

	// Seteamos el nuevo currency
	var request = new Request.JSON({
		url: '/ajax/class/Currency/setCurrency/'+newCurrency
	}).send();
}

function activateCurrency (item) {
	//changeCurrency(item.getProperty('currency'));
	var liCurrent = $('li-currency-'+item.getProperty('currency')).dispose().clone();
	// Desmarco el anterior como current
	$$('#currency ul li.current').removeClass('current');
	liCurrent.setProperty('id', 'li-currency-'+item.getProperty('currency')).addClass('current').inject($('currency').getElement('ul'), 'top');
	closeCurrency();
	changeCurrency(item.getProperty('currency'));
}

function beginCurrency () {
	if ($('currency')) {
	    $('currency').addClass('opened');
	    
		$$('#currency ul li a').each(function(item){
			if (!item.getParent().hasClass('class')) {
				item.addEvent('click', function(ev){
					new Event(ev).stop();

					//changeCurrency(item.getProperty('currency'));
					var liCurrent = $('li-currency-'+item.getProperty('currency')).dispose().clone();
					// Desmarco el anterior como current
					$$('#currency ul li.current').removeClass('current');
					liCurrent.setProperty('id', 'li-currency-'+item.getProperty('currency')).addClass('current').inject($('currency').getElement('ul'), 'top');
					closeCurrency();
					changeCurrency(item.getProperty('currency'));
				});
			}
		});
	}
	
}

function selectCurrency () {
}

function openCurrency () {

	if ($('currency')) {
		$('currency').getElements('li').each(function(item){
			item.setStyle('display', 'inline');
		});
	}

	beginCurrency();

	// Cierro el carrito con el boton escape
	document.removeEvents('keydown').addEvents({
		'keydown': function(ev){ 
			if (ev.key == 'esc') {
				closeCurrency();
			}
		},
		'click': function(ev){ 
				closeCurrency();
		}
	});
}

function closeCurrency () {
	if ($('currency'))
		$('currency').getElements('li').each(function(item, index){
			if (index > 0) {
				if (!item.hasClass('last'))
					item.getFirst().removeEvents('click');
				item.setStyle('display', 'none');
			}
		});
	document.removeEvents('keydown');
	document.removeEvents('click');
	
	$('currency').removeClass('opened');
	
	if ($('currency')) {
		$$('#currency ul li.current a').addEvent('click', function (ev) {
			new Event(ev).stop();
			openCurrency();
		});
	}
}

/*
window.addEvent('resize', function() {      
	if ($('currency')) $('currency').setStyle('left', $('container').getPosition().x + 730);
});
*/

/*
document.addEvent('load', function() {
	new Element('script', {'src': 'http://www.avantrip.com/chat/js/status_image.php?base_url=http://www.avantrip.com/chat&l=betatrip&x=1&deptid=1&text=Chat Online', 'type': 'text/javascript'}).inject($('scripts-container'), 'bottom');
	chatLoaded = true;
});
*/

document.addEvent('domready', function(){
	
var inicio = new Date();
/*
  var arrLazyLoadScripts = ['/javascripts/k_push.js', '/javascripts/k_button.js'];
  for (var i = 0; i < arrLazyLoadScripts.length; i++) {
//alert(arrLazyLoadScripts[i]);
//	new Element('script', {'src': arrLazyLoadScripts[i], 'type': 'text/javascript'}).inject($('scripts-container'), 'bottom');    
      // Obtenemos el jsessionid y seteamos el action del formulario
      var request = new Request.HTML({
        url: arrLazyLoadScripts[i],
	onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript) {
	  new Element('script', {'html': responseHTML, 'type': 'text/javascript'}).inject($('scripts-container'), 'bottom');
	}
      }).send();
  }
*/

	//var currencyTable = new Hash();
//alert(currencyTable['ARS'].code);
	if ($('currency')) {
	   // $('currency').setStyle('left', $('container').getPosition().x + 730);
		$$('#currency ul li.current a').addEvent('click', function (ev) {
			new Event(ev).stop();
			openCurrency();
		});
//		changeCurrency($$('#currency ul li.current a').getProperty('currency'));
	}
	//setCurrency(currencyDefault);

/*
	if ($('change-currency') && $$('.price'))
		$('change-currency').getElements('a').each(function(item){
			item.addEvent('click', function(ev){
				new Event(ev).stop();
				changeCurrency(item.getProperty('to'));
			});
		});
*/
var fin = new Date();
//alert('Tardo: '+(fin-inicio));
});

	function close_error (inp) {
		if ($('error-template'))
			$('error-template').setStyle('display', 'none');
	}

	function show_error (myInput, myMsg) {

		// Creo el div de error si no existe
		if (!$('error-template')) {
			new Element('div', {'id': 'error-template', 'class': 'error-msg'}).set('html', '<div class="content"><ul><li class="left">&nbsp;</li><li class="center"><span class="msg"></span><a class="close">[x]</a></li><li class="right"></li></ul></div>').inject(document.body, 'bottom');
		}

		var errorDiv = $('error-template');
		var closeDiv = errorDiv.getElement('a')
		closeDiv.addEvent('click', function(ev){
			ev = new Event(ev).stop();
			close_error();
			$(myInput).focus();
		});

		$(myInput).addEvent('blur', function(ev){
			close_error();
		});

		$(myInput).addEvent('keypress', function(ev){
			close_error();
		});

		errorDiv.getElement('span').set('text', myMsg);
		var myCoordinates = $(myInput).getCoordinates();

		errorDiv.setStyles({
			'top': myCoordinates.top-35,
			'left': myCoordinates.left+30,
			'display': 'block'
		});

		new Fx.Scroll(document, {
			wait: false,
			duration: 1000,
			offset: {'x': -200, 'y': -50},
			transition: Fx.Transitions.Quad.easeInOut
		}).toElement(myInput);

		$(myInput).focus();
		
		// estas dos lineas debajo las comente por traer problemas cuando el input es un select en google chrome
		//if ($(myInput).length) 
		//	errorDiv.getElement('a').fireEvent('click');
	}

    function createMarker(point,html, icon) {
      //var marker = new GMarker(point, icon);
      var marker = new GMarker(point, icon);
      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }

		function addGeoPoint(gp, cart) {
			if (!cart) cart = CartMap;
if (!$('geopoint-'+geoPointCount))return;
//alert(geoPointCount);
      ++geoPointCount;
      var point = new GLatLng(gp.lat, gp.lng);
      var marker = createMarker(point,'<div style="width:240px">'+gp.title+'<\/div><div class=""><ul><li><a href="#" onClick="javascript:zoomIn('+gp.lat+', '+gp.lng+');return false;">zoom in</a></li><li><a href="#" onClick="javascript:zoomOut();return false;">zoom out</a></li></ul></div>');
      cart.addOverlay(marker);
if ($('geopoint-'+geoPointCount)) {
      $('geopoint-'+geoPointCount).addEvent('click', function(ev){
      	new Event(ev).stop();
				new Fx.Scroll(document, {
					wait: false,
					duration: 1000,
					offset: {'x': -200, 'y': -50},
					transition: Fx.Transitions.Quad.easeInOut
				}).toTop();
				GEvent.trigger(marker,'click'); 
      });
}
else
;//alert(geoPointCount);
    	bounds.extend(point);
		}
		
		function zoomIn(lat,lng, thisMap) {
			if (!thisMap) thisMap = map;
		  var zoom = thisMap.getZoom();
		  zoom = Math.min(15,zoom+1);
		  zoom = Math.max(13,zoom);
		  thisMap.setCenter(new GLatLng(lat,lng),zoom);
		}

		function zoomOut(thisMap) {
			if (!thisMap) thisMap = map;
      thisMap.setZoom(thisMap.getBoundsZoomLevel(bounds));
      thisMap.setCenter(bounds.getCenter());
		}


/*
		function addGeoPoint(gp) {
      ++geoPointCount;
      var point = new GLatLng(gp.lat, gp.lng);
      var marker = createMarker(point,'<div style="width:240px">'+gp.title+'<\/div><div class=""><ul><li><a href="#" onClick="javascript:zoomIn('+gp.lat+', '+gp.lng+');return false;">zoom in</a></li><li><a href="#" onClick="javascript:zoomOut();return false;">zoom out</a></li></ul></div>');
      map.addOverlay(marker);
      $('geopoint-'+geoPointCount).addEvent('click', function(ev){
      	new Event(ev).stop();
				GEvent.trigger(marker,'click'); 
      });
    	bounds.extend(point);
		}
		
		function zoomIn(lat,lng) {
		  var zoom = map.getZoom();
		  zoom = Math.min(15,zoom+1);
		  zoom = Math.max(13,zoom);
		  map.setCenter(new GLatLng(lat,lng),zoom);
		}

		function zoomOut() {
      map.setZoom(map.getBoundsZoomLevel(bounds));
      map.setCenter(bounds.getCenter());
		}
*/

	// Funcion de countdown de para el checkout, despue hay que limpiarla y hacerla generica
	function countdown2 (index) {
		var countdownCont = $(clocks[index]);
		// Obtengo horas, minutos y segundos del reloj
		var params = countdownCont.get('text').toString().split(":");

		// seteo sec, min, hour
		var min = params[0].toInt();
		var sec = params[1].toInt()-1;

		// los segundos pasaron el 0, resto minutos
		if (sec < 0) {
			sec = 59;
			--min;
		}

		// Seteo el nuevo tiempo
		countdownCont.set('text', pad_left(min.toString())+':'+pad_left(sec.toString()));

		// Si llegue a 00:00:00 aborto
		if ((min < 0) || (sec < 0) || ((min == 0) && (sec == 0))) {
//alert('aa');
			clearInterval(intervalID[index]);
			countdownCont.set('text', '00:00');
		}
	}




