$(function() {  
  $('tr.odd, tr.even').mouseover(function() {  
       $(this).addClass("overrow").show("slow");  
  } )  
  $('tr.odd, tr.even').mouseout(function() {  
      $(this).removeClass("overrow").show("slow");  
  } )

	
     //cache nav  
	 var nav = $("#menu");  

	 //add indicators and hovers to submenu parents  
	 nav.find("li").each(function() {  
		 if ($(this).find("div").length > 0) {  		 

			 //show subnav on hover  
			 $(this).mouseenter(function() {  
				 $(this).find("div").stop(true, true).slideDown();  
			 });  

			 //hide submenus on exit  
			 $(this).mouseleave(function() {  
				// $(this).find("div").stop(true, true).slideUp();  
				 $(this).find("div").hide();
			 });  
		 }  
	 });  	 
})

function doSubmit(id_form, action){
	$("#"+id_form).attr('action', action);
	$("#"+id_form).submit();
}

function doValid(id_form, action){
	
	if(initValidation(id_form)){	
		$("#"+id_form + "#img_enviar").hide();
		doSubmit(id_form, action);		
	}
}

function initValidation (id_form){

	var correcto = true;	
	// campos requeridos
	  $("#"+id_form).find(".required:visible").each(function(i) {
															 
		id = $(this).attr("id");
	   valor=$(this).val();

	   if (valor==undefined || valor=="" || valor=="void"){
		   
	   	   mark_field(id,'required');
		  
		   correcto = false;		
	   }else 
	   		unmark_field(id,'required');
     
	   });
	  
	  
	    
	   // checkbox ----------------------------------------------
	var	k=0;	 
	var	numero_total=false;
	var checbox_validar = false;
	
	// buscamos todos los checkbox que tengan la clase required_check
	   $("#"+id_form).find(".required_check:visible").each(function(i) {
		id = $(this).attr("id");
		 
	  	// cogemos el id de cada uno y buscamos la longitud
	    var checked = $("input[@id="+id+"]:checked").length; 
        if (checked == 0) { k++; } // sumamos uno al contador si encontramos vacío
		
		numero_total++;
		checbox_validar = true;

	   });

	
		
	   if(true == checbox_validar && k==numero_total){ // comprobamos si hay como mínimo 1 seleccionado, de no ser así mostramos error
		correcto = false;
		 //mark_field(id,'required');
	 	$("#checkboxes_error").show();
	   }else{

		   $("#checkboxes_error").hide();
	   }
	   // FIN checkbox ----------------------------------------------
	 

     
	  
	// Aceptar condiciones	
	if($("#"+id_form + " #accept_cond").attr("value") != undefined && $("#"+id_form + " #accept_cond:checked").val() == null){		
		mark_field('accept_cond','required');
	   correcto = false;
	}else{
		unmark_field('accept_cond','required');
	}
	  
	// campos password iguales	  
	pasw = $("#"+id_form + " #password").val();		
	repasw = $("#"+id_form + " #repassword").val();	
	
	if(pasw != undefined && pasw != ''){
		if (pasw == repasw){
   			unmark_field('password','match_password');  		
	   }else{ 
   		   mark_field('password','match_password');
		   correcto = false;
	   }  	
	}
	   
	  
	 
	// campos email
	$("#"+id_form).find(".valid_email:visible").each(function(i) {	
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	  
	   if (valor!=undefined) {
	  if (!valor.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$/i)){
	  	mark_field(id,'valid_email');
		correcto = false;
	  }else unmark_field(id,'valid_email');
	   }
	   });
	   
	 // min length
	 $("#"+id_form).find(".min_length:visible").each(function(i) {		
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	  if (valor!=undefined) {
	  if (valor.length<6){
	  	mark_field(id,'min_length');
		correcto = false;
	  }
	   else unmark_field(id,'min_length');
	  }
	   });

	 $("#"+id_form).find(".minimum:visible").each(function(i) {			 
		id = $(this).attr("id");
	   valor=$(this).attr("value");
	  if (valor!=undefined) {
	  	id = $(this).attr("id");
	  	fieldcomp = id.substring(0, id.indexOf('_') );
	  	
	  	valor2=$("#"+fieldcomp).attr("value");
	  
	  	if (parseInt(valor)>parseInt(valor2)){
	  	correcto = false;
	  	mark_field(id,'minimum');
		}
	   else unmark_field(id,'minimum');
	  }
	   }); 	  
	   
	  if(correcto == false){  $('#' + id_form + ' .shake').vibrate(); }

	 return correcto;
}


function mark_field (id, type)
{	
	$("#"+id).css("background-color", "#9DB7D2");	
	//document.getElementById(id).style.backgroundColor="#ffffcc";
	//$("#"+id).addClass('fondo');
	
	/* This is used for the Sign Up form. I'm not sure if it's ok to call if in the Admin section*/	
	/*I'm not sure of this. May ask Jordi. I'm using the vibrate function :) */
	

	$("#error_all_" + type).show();	
}

function unmark_field (id, type)
{	
	$("#"+id).css("background-color", "#FFFFFF");
	$("#error_"+ id + "_" + type).hide();
	//$("../",id).remove("span");
}

						
function borrar_opcion(text){
	if(confirm(text)){
		return true;
	}else return false;
}

function popup(page, title, width, height) {	
	window.open(page, title, "width=" + width + ",height="+height+",menubar=no,scrollbars=yes");
}

function doPost (uri, field_name, field_value)
{
	idForm=Math.round(Math.random()*10);
	
	htmlForm = "<form id='dyn_form_"+idForm+"' action='"+uri+"' method='POST'>";
	htmlForm+= "<input type='hidden' name='"+field_name+"' value='"+field_value+"' >";
	htmlForm+= "</form>";
	
	$("body").append(htmlForm);
	$("#dyn_form_"+idForm).submit();
}

function doPost_blank (uri, field_name, field_value)
{
	idForm=Math.round(Math.random()*10);
	
	htmlForm = "<form id='dyn_form_"+idForm+"' action='"+uri+"' method='POST' target='_blank'>";
	htmlForm+= "<input type='hidden' name='"+field_name+"' value='"+field_value+"' >";
	htmlForm+= "</form>";
	
	$("body").append(htmlForm);
	$("#dyn_form_"+idForm).submit();
}

function doPostMultiple (uri, array_fields)
{
	idForm=Math.round(Math.random()*10);
	
	htmlForm = "<form id='dyn_form_"+idForm+"' action='"+uri+"' method='POST'>";
	var i=0;
	for(i=0; i<array_fields.length; i=i+2){
		htmlForm+= "<input type='hidden' name='"+array_fields[i]+"' value='"+array_fields[i+1]+"' >";
	}
	htmlForm+= "</form>";
	
	$("body").append(htmlForm);
	$("#dyn_form_"+idForm).submit();
}


function OFlash (file, width, height, bgcolor, mode) { document.write ("<object codeBase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=4,0,2,0 height=" + height + " width=" + width + " classid=clsid:D27CDB6E-AE6D-11cf-96B8-444553540000><PARAM NAME='FlashVars' VALUE=''><PARAM NAME='Movie' VALUE='" + file + "'><PARAM NAME='Src' VALUE='" + file + "'><PARAM NAME='WMode' VALUE='" + mode + "'><PARAM NAME='Play' VALUE='-1'><PARAM NAME='Loop' VALUE='-1'><PARAM NAME='Quality' VALUE='High'><PARAM NAME='SAlign' VALUE=''><PARAM NAME='Menu' VALUE='0'><PARAM NAME='Base' VALUE=''><PARAM NAME='AllowScriptAccess' VALUE='0'><PARAM NAME='Scale' VALUE='ShowAll'><PARAM NAME='DeviceFont' VALUE='0'><PARAM NAME='EmbedMovie' VALUE='0'><PARAM NAME='BGColor' VALUE='" + bgcolor +"'><PARAM NAME='SWRemote' VALUE=''><PARAM NAME='MovieData' VALUE=''><PARAM NAME='SeamlessTabbing' VALUE='1'><PARAM NAME='Profile' VALUE='0'><PARAM NAME='ProfileAddress' VALUE=''><PARAM NAME='ProfilePort' VALUE='0'><embed src='" + file + "' quality=high pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='" + width + "' height='" + height +"'  wmode= '"+mode+"'></embed></object>"); }


function go_back(){
	history.back();
}

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}


 function DiferenciaFechas (first, second, tiempo) {  
   
    //Obtiene los datos del formulario  
    CadenaFecha1 = $("#"+first).val(); 
    CadenaFecha2 = $("#"+second).val();
      
    //Obtiene dia, mes y año  
    var fecha1 = new fecha( CadenaFecha1 );
    var fecha2 = new fecha( CadenaFecha2 ); 
      
    //Obtiene objetos Date  
    var miFecha1 = new Date( fecha1.anio, fecha1.mes, fecha1.dia ); 
    var miFecha2 = new Date( fecha2.anio, fecha2.mes, fecha2.dia ); 
   
    //Resta fechas y redondea  
    var diferencia = miFecha1.getTime() - miFecha2.getTime();  
    var dias = Math.floor(diferencia / (1000 * 60 * 60 * 24));  
    var segundos = Math.floor(diferencia / 1000);  
		
		if(dias>tiempo){
			alert ('No puedes seleccionar un rango de fechas mayor a '+tiempo);  			
			return false;
		}

      
    return true;  
 }  
   
 function fecha( cadena ) {  
   
    //Separador para la introduccion de las fechas  
    var separador = "-";
   
    //Separa por dia, mes y año  
    if ( cadena.indexOf( separador ) != -1 ) {  
         var posi1 = 0;  
         var posi2 = cadena.indexOf( separador, posi1 + 1 );  
         var posi3 = cadena.indexOf( separador, posi2 + 1 ); 
         this.dia = cadena.substring( posi1, posi2 );
         this.mes = cadena.substring( posi2 + 1, posi3 );
         this.anio = cadena.substring( posi3 + 1, cadena.length );
    } else {  
         this.dia = 0;
         this.mes = 0; 
         this.anio = 0;     
    }  
	
	
 }
 
 function ir_a(location){
	 parent.location.href=location;
 }
 
 function desplegar(id_div){
	$('#'+id_div+"_desplegable").toggle();
	var top = parseInt($('#btn_'+id_div).offset().top)-parseInt($('#'+id_div+"_desplegable").height());
	$('#'+id_div+"_desplegable").css("top", top);
}

function div_subgeneros_tienda_admin(nombre_select, subgenero_select){
	var id_genero = $("#PGenero").val();
	
	html = $.ajax({
		type: "POST",
		url: '/admin/tienda/update_subgeneros/'+id_genero+'/'+nombre_select + '/'+subgenero_select,
		async: false
	 }).responseText;	
	 
	 $("#div_subgeneros").html(html);}
	 
	 
/* Overlay */	 
$(document).ready(function() {

	var triggers = $(".modalInput").overlay({
	
		// some mask tweaks suitable for modal dialogs
		mask: {
			color: '#D3D3D3',
			loadSpeed: 100,
			opacity: 0.8
		},
	
		closeOnClick: false
	});


	/*$("#prompt form").submit(function(e) {
	
		// close the overlay
		triggers.eq(1).overlay().close();
	
		// do not submit the form
		return e.preventDefault();
	});*/

});




$(function() { 
	$("#acordeon1").tabs("#acordeon1 div.pane", {tabs: 'h2', effect: 'slide', initialIndex: null});
});


function toggle_him(id){
		
	  $(".flecha").attr("src", "/public/img/f_hor.png");
  	  $(".f_"+id).attr("src", "/public/img/f_ver.png");
	  $(".t_link").removeClass('naranja');
	  $(".t_link_"+id).addClass('naranja');	  
	  $(".tienda_contendio").slideUp('slow');
	  $("#contenido_"+ id).slideDown('slow');
	
}

function select_store(store_id){
	
	$(".bullet").attr("src", "/public/img/bullet.png");
	$('#store_id').attr('value', store_id);	
	$("#bullet_"+store_id).attr("src", "/public/img/bullet_selected.png");
		
}

function change_price(id_item, price_material, precio_suplemento, price_material_tienda, precio_suplemento_tienda, precio_suplemento_2, precio_suplemento_tienda_2){

	if ($('#suplemento_'+id_item+':checked').val() != null) {
		price_material = parseFloat(precio_suplemento);
		price_material_tienda = parseFloat(precio_suplemento_tienda);	
	}
	
		if ($('#suplemento_'+id_item+'_2:checked').val() != null) {
			
			price_material = parseFloat(price_material) + parseFloat(precio_suplemento_2);
			price_material_tienda = parseFloat(price_material_tienda) + parseFloat(precio_suplemento_tienda_2);
			
		}
			
	
		$("#precio_"+id_item).html(price_material);
		$("#precio_tienda_"+id_item).html(price_material_tienda);

	
}


$.fn.vibrate = function (conf) {
    var config = $.extend({
        speed:        10, 
        duration:    500, 
        frequency:    0, 
        spread:        5
    }, conf);

    return this.each(function () {
        var t = $(this);

        var vibrate = function () {
           // var topPos    = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);
            var leftPos    = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);
           // var rotate    = Math.floor(Math.random() * config.spread) - ((config.spread - 1) / 2);

            t.css({
                position:            'relative', 
                left:                leftPos + 'px', 
                top:                '0px', 
                WebkitTransform:    'rotate(0deg)' 
            });
        };

      
		var stopVibration = function () {
                clearInterval(vibrationInterval);
                $(t).stop(true,false).css({position: 'static', left: '0px', top: '0px'});
				

        };

       	 var vibrationInterval = setInterval(vibrate, config.speed);
		 setTimeout(stopVibration, config.duration);
			   
    });
};

function enviar_bono_pedido(id_pedido, para_quien){
	html = $.ajax({
		type: "POST",		
		url: "/admin/pedidos/enviar_bono_pedido/"+id_pedido+"/"+para_quien,
		async: false
	 }).responseText;	
	alert('Se ha enviado el bono a '+para_quien);
}

function comprobar_registro(id_form, action){
	if(initValidation(id_form) && comprobar_email_unico('CEmail') == 'si'){	
		$("#"+id_form + "#img_enviar").hide();
		doSubmit(id_form, action);		
	}	
}

function comprobar_email_unico(id_field){
	email = $("#"+id_field).val()
	html = $.ajax({
		type: "POST",
		data: "email="+email,
		url: "/home/comprobar_email_unico/",
		async: false
	 }).responseText;
	 
	 if(html == 'no'){
		 $("#campos_obligatorios .error").show();
		 mark_field(id_field, 'required');
	 }
	 return html;
}

function change_price_ficha(precio){
	var id_articulo = $("#talla_referencia").val();
	var cantidad = $("#cantidad_referencia").val();
	
	$("#precio_total").html(((cantidad*100)*precio)/100 + " &euro;");
}

function change_articulo_cantidad(){
	var id_articulo = $("#talla_referencia").val();
	var cantidad = $("#cant_"+id_articulo).val();
	var prec = $("#prec_"+id_articulo).val();
	var prec_normal = $("#prec_normal_"+id_articulo).val();
	
	var select = $('#cantidad_referencia');
	var options = select.attr('options');
	$('option', select).remove();
	
	//alert(cantidad);
	for(i=0; i<=cantidad; i=i+1){
		$('#cantidad_referencia').append('<option value="'+i+'">'+i+'</option>');
	};

	$("#text_referencia").html(id_articulo);
	var html = "";
	if(prec != prec_normal){
		html = '<span class="outer"><span class="inner">'+prec_normal+' &euro;</span></span><br>'+prec + ' &euro;';
	}else{
		html = prec + " &euro;";
	}
	$("#precio_referencia").html(html);
	$("#precio_total").html("");
}

function select_tienda_paso1(store_id, my_lang, estacion_id){
	
	// all default pins
	$('.pins').attr('src', '/public/img/map_pin.png');
	
	// Activate Pin	
	$('#overlay_pin_'+store_id).attr('src', '/public/img/map_pin_active.png');
	
	// just if is needed
	
	if(estacion_id != ""){
	
		$('#pin_'+estacion_id).attr('src', '/public/img/map_pin_active.png');
	}
	
	// hidden value
	$('#store_id').attr('value', store_id);
	
	// Ajax para el text -> Oh my…
		
	params = 'id_store='+store_id+"&my_lang="+my_lang;
	
	html = $.ajax({
		type: "POST",
		data: params,
		url: '/alquiler/give_me_store_name',
		async: false
	 }).responseText;	
	 
	 $('#tienda_seleccionada_texto').html(html);
	 $('.close').click();
		
	
}

function show_estacion_map(id_map){

	$('.estacion_map').hide();
	$('#mapa_'+id_map).show();
	

}
