/* Tab */

function loadTab(){
 	//Default Action
	$(".tab_content").hide(); //Hide all content
	
	$("ul.tabs li:first a").addClass("selected").show(); //Activate first tab
	$("ul.tabs li:first").addClass("selected").show(); //Activate first tab
	
	$("ul.tabs-hover li:first a").addClass("selected").show(); //Activate first tab
	$("ul.tabs-hover li:first").addClass("selected").show(); //Activate first tab*/
	
	
	$(".tab_content:first").show(); //Show first tab content
	
	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li a").removeClass("selected"); //Remove any "active" class
		$("ul.tabs li").removeClass("selected"); //Remove any "active" class
		
		$(this).find("a").addClass("selected"); //Add "active" class to selected tab
		$(this).addClass("selected"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
	
	//on over event
	$("ul.tabs-hover li").mouseenter(function() {
		//active tab = tab wanted?
		if($(this).find("a").attr("rel") == $("ul.tabs-hover li.selected a").attr("rel")) return false;
		
		$("ul.tabs-hover li a").removeClass("selected"); //Remove any "active" class
		$("ul.tabs-hover li").removeClass("selected"); //Remove any "active" class
		
		$(this).find("a").addClass("selected"); //Add "active" class to selected tab
		$(this).addClass("selected"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("rel"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active content
		return false;
	});
}

function loadTabDetalle(){
 	//Default Action
	/*$(".tab_content").hide(); //Hide all content
	
	$("ul.tabs li:first a").addClass("selected").show(); //Activate first tab
	$("ul.tabs li:first").addClass("selected").show(); //Activate first tab
	
	$("ul.tabs-hover li:first a").addClass("selected").show(); //Activate first tab
	$("ul.tabs-hover li:first").addClass("selected").show(); //Activate first tab
	
	
	$(".tab_content:first").show(); //Show first tab content*/
	
	//only show the first tab
	$("ul.tabs li:first a").addClass("selected");
	$("ul.tabs li:first").addClass("selected");
	$(".tab_content:gt(0)").addClass("hide");
	
	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li a").removeClass("selected"); //Remove any "active" class
		$("ul.tabs li").removeClass("selected"); //Remove any "active" class
		
		$(this).find("a").addClass("selected"); //Add "active" class to selected tab
		$(this).addClass("selected"); //Add "active" class to selected tab
		$(".tab_content").addClass("hide"); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).removeClass("hide");
		return false;
	});
}

/* end */
function loadSlider(_sliderBg, _tooltipMin, _tooltipMax, _inputMin, _inputMax, _minThumb, _maxThumb, _unitad, _rangeWanted, _tick) {
	YAHOO.namespace('ingvo');
	var Dom = YAHOO.util.Dom;
	// Slider has a range of 200 pixels
	var range = 200;
	var coef = _rangeWanted / range;
	// No ticks
	var tickSize = 200/_tick;
	// We'll set a minimum distance the thumbs can be from one another
	var minThumbDistance = 10;
	
	// Slider set up is done when the DOM is ready
	var slider_bg = Dom.get(_sliderBg),
		tooltipMin = Dom.get(_tooltipMin),
		tooltipMax = Dom.get(_tooltipMax),
	    from    = Dom.get(_inputMin),
	    to      = Dom.get(_inputMax),
	    minThumb = Dom.get(_minThumb),
	    maxThumb = Dom.get(_maxThumb);
	
	var initValues = [from.value/coef, to.value/coef];
	var slider = YAHOO.widget.Slider.getHorizDualSlider(_sliderBg, _minThumb, _maxThumb, range, tickSize, initValues);
	slider.minRange = minThumbDistance;
	
	var updateUI = function () {
	    from.value = slider.minVal*coef;
	    to.value   = slider.maxVal*coef;
	    tooltipMin.innerHTML = from.value + _unitad;
	    tooltipMax.innerHTML = to.value + _unitad;
	    slider_bg.title  = tooltipMin.innerHTML + " - "+tooltipMax.innerHTML;
	    
	    showToolTip(); /*JQuery UI doesnt not support to set position of hidden element!!*/
		var posMinThumb = Dom.getRegion(minThumb);
	    var posMinX = posMinThumb.left - Dom.getRegion(tooltipMin).width + 20;
	    var posMinY = posMinThumb.bottom;
	    var posMaxThumb = Dom.getRegion(maxThumb);
	    var posMaxX = posMaxThumb.left -4; //+ (Dom.getRegion(tooltipMax).width)/2;
	    var posMaxY = posMaxThumb.bottom;
	    
	    Dom.setXY(tooltipMin,[posMinX,posMinY]);
	    Dom.setXY(tooltipMax,[posMaxX,posMaxY]);
	};
	
	slider.subscribe('ready', updateUI);
	slider.subscribe('change', updateUI);
	YAHOO.ingvo.slider = slider; // Attach the slider to the YAHOO.example namespace for public probing
	
	//handle the tooltip
	function showToolTip(){
		Dom.setStyle(tooltipMin, "display", "block");
	    Dom.setStyle(tooltipMax, "display", "block");
	}
	
	function hideToolTip(){
		Dom.setStyle(tooltipMin, "display", "none");
		Dom.setStyle(tooltipMax, "display", "none");
	}
	   
	/* over */
	$(slider_bg).mouseenter(updateUI);
	
	$(slider_bg).mouseleave(hideToolTip);
};


function MyPopup(idPopup, idBackground, btOpen, btClose){
	var me = this;
	
	this.idPopup = idPopup;
	this.idBackground = idBackground;
	this.btOpen = btOpen;
	this.btClose = btClose;
	this.status = 0;

	this.displayObject = function(){
		//console.log("id:"+this.id, " status:"+this.status);
	};
	
	this.center = function(){
		var windowWidth = document.documentElement.clientWidth;
		var windowHeight = document.documentElement.clientHeight;  
		var popupHeight = $(this.idPopup).height();  
		var popupWidth = $(this.idPopup).width();  
		//centering  
		$(this.idPopup).css({  
			"position": "fixed",  
			"top": windowHeight/2-popupHeight/2,  
			"left": windowWidth/2-popupWidth/2  
		});  
		//only need force for IE6  
		$(this.idBackground).css({  
			"height": windowHeight  
		});  
	};
	
	this.show = function(){
		//console.log("show popup "+this.idPopup);
		//loads popup only if it is disabled
		if(this.status==0){  
			//me.center();
			$(this.idBackground).css({"opacity": "0.7"});  
			$(this.idBackground).fadeIn(300);  
			$(this.idPopup).fadeIn(300);  
			this.status = 1;  
		}  
		return false;
	};
	
	this.hide = function(){  
		//disables popup only if it is enabled
		//console.log("hide popup "+this.idPopup);
		if(this.status==1){  
			$(this.idBackground).fadeOut("fast");  
			$(this.idPopup).fadeOut("fast");  
			this.status = 0;  
		}
		return false;
	};
	
	this.clickOpen = function(){ 
		me.show();
		return false;
	};
	
	this.clickClose = function(){
		me.hide();
		return false;
	};
	
	/* attach events */
	this.load = function(){
		$(this.btOpen).click(this.clickOpen);
		//CLOSING POPUP  
		$(this.btClose).click(this.clickClose);  
		//Click out event!  
		$(this.idBackground).click(this.clickClose);  
	};
}

var updateHipoteca;

/* calculo hipoteca */
function loadHipoteca(){
	var hip_valor = $("#hip-valor"); //total price of the vehicle
	var hip_plazo = $("#hip-plazo"); //in months
	var hip_entrada = $("#hip-entrada"); //amount of money paid by the buyer the 1st day
	var hip_cuota = $("#hip-cuota"); //out: amount of money to be paid each month
	var rate = 8.75;
	
	var hip_error_valor = $("#hip-error-valor");
	var hip_error_entrada = $("#hip-error-entrada");
	
	hip_error_valor.hide();
	hip_error_entrada.hide();
	
	updateHipoteca=function(_pvp){
		hip_valor.val(_pvp);
		update();
	};
	
	function update(){
		if(isNumeric(hip_valor.val())) hip_error_valor.hide();
		else hip_error_valor.fadeIn();
		
		if(isNumeric(hip_entrada.val())) hip_error_entrada.hide();
		else hip_error_entrada.fadeIn();
		
		if( !isNumeric(hip_valor.val()) || !isNumeric(hip_entrada.val()) ){
			return;
		}
		var coeficiente;
		/* Sergio Tello: nueva forma de calculas las cuotas de financiacion */
		if(hip_plazo.val() == 12)
			{coeficiente=0.0902257;}
		else if (hip_plazo.val() == 24)
			{coeficiente=0.0472578;}
		else if (hip_plazo.val() == 36)
			{coeficiente=0.0330;}
		else if (hip_plazo.val() == 48)
		{coeficiente=0.0259244;}
		else coeficiente=0.0217329;
		
		var cuota = (hip_valor.val() - hip_entrada.val())*coeficiente;
		cuota = Math.round(cuota); 
		/* COMENTAMOS LA ANTERIOR FORMA DE CALCULAR LAS CUOTAS ----------
		if(hip_plazo.val() >= 84) rate=9;
		var interes = rate/12/100;
		var cuota = ((hip_valor.val() - hip_entrada.val()) * interes) / ((1- Math.pow(1+interes,-hip_plazo.val()) ) );
		
		cuota = Math.round(cuota); //*100)/100;
		
		----------------------------------------------------------------*/
		
		
		
		
		//console.debug("rate:"+rate+" val:" + hip_valor.val() + " pla: " + hip_plazo.val() + " entr:" + hip_entrada.val() + "interes" + interes + " -> cuota:" + cuota);
		
		hip_cuota.val(cuota + $("#hip-euro").val());
	};
	
	$("#hipoteca-ok").click(update);
	$(hip_valor).keyup(update);
	$(hip_entrada).keyup(update);
	$(hip_plazo).change(update);
	
	update();
}

var updateSeguro;

function loadSeguro(){
	//input
	var pvp = $("#seg-pvp");
	var edad = $("#seg-edad");
	
	//output
	var tercero = $("#seg-tercero");
	var terceroMas = $("#seg-tercero-mas");
	var todoRiesgo300 = $("#seg-todo-riesgo-300");
	var todoRiesgo = $("#seg-todo-riesgo");
	
	var divRes = $("#seguro-resultado");
	var divRes30 = $("#seguro-resultado-menos-30");
	
	//err
	var seg_pvp_err=$("#seg-pvp-err");
	
	var euro = $("#seg-euro").val();
	
	var tarifa = [
	              [ //-30 anos
	               ["pdte", "pdte", "pdte", "pdte"], //-20keur
	               ["pdte", "pdte", "pdte", "pdte"], //20-40keur
	               ["pdte", "pdte", "pdte", "pdte"] //+40keur
	              ],
	              [ //30-50anos
		           [364,500,790,989],
		           [398,546,867,1081],
		           [481,628,1051,1265]
		          ],
		           [ //+50anos
			        [293,403,639,797],
			        [321,440,699,871],
			        [388,506,847,1019]
			      ]
	              ];
	               
	
	$(pvp).keyup(update);
	$(edad).change(update);
	
	
	updateSeguro= function(_pvp){
		pvp.val(_pvp);
		update();
	};
	
	function update(){
		
		if(isNumeric(pvp.val())) seg_pvp_err.hide();
		else seg_pvp_err.fadeIn();
		
		if(!isNumeric(edad.val())){
			divRes.hide();
			divRes30.hide();
			return;
		}
		
		var i = edad.val();

		if(i==0){ //menos que 30 anos
			divRes.hide();
			divRes30.show();
		}else{ //otros casos
			divRes.show();
			divRes30.hide();
			var j;
			if(pvp.val() < 20000) j = 0;
			if(pvp.val() >= 20000 && pvp.val()<=40000) j=1;
			if(pvp.val() > 40000) j = 2;
			
			var tarifaEdadPvp = tarifa[i][j];
			tercero.val(tarifaEdadPvp[0]+euro);
			terceroMas.val(tarifaEdadPvp[1]+euro);
			todoRiesgo300.val(tarifaEdadPvp[2]+euro);
			todoRiesgo.val(tarifaEdadPvp[3]+euro);
		}
	};
}

function isNumeric(input){
   return (input - 0) == input && input.length > 0;
}

function loadPrintButton(){
	$("#print").click(function(){
		window.print();
		//$(".contenido_right").print();
		return false;
	});
}

/* show hide indicator working */
function showLoadingModelos(data){
	showIndicatorRegion(data, "#loadingModelos");
}

function showLoadingResults(data){
	loadDragAndDrop();
	showIndicatorRegion(data, "#loading-results");
}

function showLoadingComparador(data){
	showIndicatorRegion(data, "#loading-comparador");
}

function showIndicatorRegion(data, regionId){
	if (data.status == "begin"){
		$(regionId).show();
	}else if(data.status == "success"){
		$(regionId).hide();
	}
}

function clickNext(id){
	$(id).next().click();
	$(id).next().css("background", "yellow");
}

/* drag and drop */
function loadDragAndDrop(){
	$(".draggable").draggable({
		zIndex: 50,
		revert:true,
		cursor:"move"
	});
	
	$("#droppable").droppable({
		accept: ".draggable",
		activeClass: "droppable-active",
		hoverClass: "droppable-hover",
		drop: function( event, ui ) {
			if(ui.draggable.attr("rel")=="colocame"){
				ui.draggable.prev().click();
				ui.draggable.hide();
			}else{
				if(!ui.draggable.parent().parent().parent().find(".comp > input:checkbox").attr('checked'))
					ui.draggable.parent().parent().parent().find(".comp > input:checkbox").click();
			}
			$(this).addClass( "droppable-highlight" );
			
		}
	});
	
	/*cursor */
	$('.draggable').hover(function() {
		$(this).css('cursor','move');
	}, function() {
		$(this).css('cursor','auto');
	});
}

function editLastDatatableRow(){
   jQuery('.ui-datatable-data tr').last().find('span.ui-icon-pencil').each(function(){
      jQuery(this).click();
   });
}

function loadPickList(_path){
	var path = _path;
	var random = (new Date().getTime());

	jQuery("li.ui-picklist-item").mousemove( function(e) {
		   var img = path+jQuery(this).html()+ random;
		   jQuery("#tooltip-img-src").attr("src",img);
		   
		   jQuery("#tooltip-img").show();
		   jQuery("#tooltip-img").css({
			   //'position': 'relative',
			   'left': e.pageX+10,
			   'top': e.pageY+10
			});
	});
	
	jQuery("li.ui-picklist-item").mouseout(function(){
		 jQuery("#tooltip-img").hide();
	});
	
}

/*function nocacheImage(){
	for (var img in jQuery("img.nocache")){
		img = jQuery(img);
		var newsrc = img.attr("src")+(new Date().getTime());
		img.attr("src",newsrc);
	};
}*/



