//JQUERY.JCLOCK PLUGIN
(function($) {

  $.fn.jclock = function(options) {
    var version = '2.1.1'; //modificado por gilbert para trabajar con warner
    // options
	
			var formattmp = "";
		//alert(clocktimedisplayformat);
		//if(!clocktimedisplayformat) var clocktimedisplayformat = "";
		
		switch(clocktimedisplayformat){
			case "24HS":
				formattmp = '%d %b | %H:%M'+"HS";
			break;
			case "AMPM":
				formattmp = "%A %d.%B.%Y&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%I:%M%p";
			break;
			case "24H":
				formattmp = '%d %b | %HH%M';
			break;
		}	
	
	$.fn.jclock.defaults = {
    format: formattmp, 
    utc_offset: 0,
    utc: false,
    fontFamily: '',
    fontSize: '',
    foreground: '',
    background: ''
  };
	
	
	
    var opts = $.extend({}, $.fn.jclock.defaults, options);  
    return this.each(function() {
      $this = $(this);
      $this.timerID = null;
      $this.running = false;

      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

      $this.format = o.format;
      $this.utc = o.utc;
      $this.utc_offset = o.utc_offset;

      $this.css({
        fontFamily: o.fontFamily,
        fontSize: o.fontSize,
        backgroundColor: o.background,
        color: o.foreground
      });

      // %a
      $this.daysAbbrvNames = new Array(7);
      $this.daysAbbrvNames[0]  = "Sun";
      $this.daysAbbrvNames[1]  = "Mon";
      $this.daysAbbrvNames[2]  = "Tue";
      $this.daysAbbrvNames[3]  = "Wed";
      $this.daysAbbrvNames[4]  = "Thu";
      $this.daysAbbrvNames[5]  = "Fri";
      $this.daysAbbrvNames[6]  = "Sat";

      // %A
      $this.daysFullNames = new Array(7);
      $this.daysFullNames[0]  = "Domingo";
      $this.daysFullNames[1]  = "Lunes";
      $this.daysFullNames[2]  = "Martes";
      $this.daysFullNames[3]  = "Miércoles";
      $this.daysFullNames[4]  = "Jueves";
      $this.daysFullNames[5]  = "Viernes";
      $this.daysFullNames[6]  = "Sabado";

	// %b
	$this.monthsAbbrvNames = new Array(13);
	$this.monthsAbbrvNames[0] = "";
	$this.monthsAbbrvNames[1] = {"esp": "ene", "por":"jan"};
	$this.monthsAbbrvNames[2] = {"esp": "feb", "por":"fev"};
	$this.monthsAbbrvNames[3] = {"esp": "mar", "por":"mar"};
	$this.monthsAbbrvNames[4] = {"esp": "abr", "por":"abr"};
	$this.monthsAbbrvNames[5] = {"esp": "may","por":"mai"};
	$this.monthsAbbrvNames[6] = {"esp": "jun", "por":"jun"};
	$this.monthsAbbrvNames[7] = {"esp": "jul", "por":"jul"};
	$this.monthsAbbrvNames[8] = {"esp": "ago", "por":"ago"};
	$this.monthsAbbrvNames[9] = {"esp": "sep", "por":"set"};
	$this.monthsAbbrvNames[10] = {"esp": "oct", "por":"out"};
	$this.monthsAbbrvNames[11] = {"esp": "nov", "por":"nov"};
	$this.monthsAbbrvNames[12] = {"esp": "dic", "por":"dez"};	  

      // %B
      $this.monthsFullNames = new Array(12);
      $this.monthsFullNames[0]  = "January";
      $this.monthsFullNames[1]  = "February";
      $this.monthsFullNames[2]  = "March";
      $this.monthsFullNames[3]  = "April";
      $this.monthsFullNames[4]  = "May";
      $this.monthsFullNames[5]  = "June";
      $this.monthsFullNames[6]  = "July";
      $this.monthsFullNames[7]  = "August";
      $this.monthsFullNames[8]  = "September";
      $this.monthsFullNames[9]  = "October";
      $this.monthsFullNames[10] = "November";
      $this.monthsFullNames[11] = "December";

      $.fn.jclock.startClock($this);

    });
  };
       
  $.fn.jclock.startClock = function(el) {
    $.fn.jclock.stopClock(el);
    $.fn.jclock.displayTime(el);
  }

  $.fn.jclock.stopClock = function(el) {
    if(el.running) {
      clearTimeout(el.timerID);
    }
    el.running = false;
  }

  $.fn.jclock.displayTime = function(el) {
	clocksecond = parseInt(clocksecond);
	clocksecond++;
	if(clocksecond==60){
		clocksecond = 0;
		clockminute = parseInt(clockminute);
		clockminute++;
		if(clockminute == 60){
			clockminute	 = 0;
			clockhour = parseInt(clockhour);
			clockhour++;
			if(clockhour == 24){
				clockhour = 0;	
			}
		}
	} 
    var time = $.fn.jclock.getTime(el);
    el.html(time);
    el.timerID = setTimeout(function(){$.fn.jclock.displayTime(el)},1000);
  }

  $.fn.jclock.getTime = function(el) {
    var now = new Date();

    if(el.utc == true) {
      var localTime = now.getTime();
      var localOffset = now.getTimezoneOffset() * 60000;
      var utc = localTime + localOffset;
      var utcTime = utc + (3600000 * el.utc_offset);
      now = new Date(utcTime);
    }

    var timeNow = "";
    var i = 0;
    var index = 0;
    while ((index = el.format.indexOf("%", i)) != -1) {
      timeNow += el.format.substring(i, index);
      index++;

      // modifier flag
      //switch (el.format.charAt(index++)) {
      //}
      
      var property = $.fn.jclock.getProperty(now, el, el.format.charAt(index));
      index++;
      
      //switch (switchCase) {
      //}

      timeNow += property;
      i = index
    }

    timeNow += el.format.substring(i);
    return timeNow;
  };

  $.fn.jclock.getProperty = function(dateObject, el, property) {
    switch (property) {
      case "a": // abbrv day names
          return (el.daysAbbrvNames[dateObject.getDay()]);
      case "A": // full day names
          return (el.daysFullNames[dateObject.getDay()]);
      case "b": // abbrv month names
          return (el.monthsAbbrvNames[clockmonth][idlanguage]);
      case "B": // month 01-12
          return (dateObject.getMonth()+1);
      case "d": // day 01-31
          return ((clockday <  10) ? "0" : "") + clockday;
      case "H": // hour as a decimal number using a 24-hour clock (range 00 to 23)
          return ((clockhour <  10) ? "0" : "") + clockhour;
      case "I": // hour as a decimal number using a 12-hour clock (range 01 to 12)
          var hours = (clockhour % 12 || 12);
          return ((hours <  10) ? "0" : "") + hours;
      case "M": // minute as a decimal number
          return ((clockminute <  10) ? "0" : "") + clockminute;
      case "p": // either `am' or `pm' according to the given time value,
		// or the corresponding strings for the current locale
          return (clockhour < 12 ? "AM" : "PM");
      case "S": // second as a decimal number
          return ((clocksecond <  10) ? "0" : "") + clocksecond;
      case "y": // two-digit year
          return ""; // TODO
      case "Y": // full year
        return (dateObject.getFullYear());
      case "%":
          return "%";
    }

  }
})(jQuery);
//END JQUERY.JCLOCK PLUGIN

//LOCALID
function localiddataresult(data){
	clocktimedisplayformat = data.timedisplayformat;
	clockweekday = Number(data.weekday);
	clockyear = data.year;
	clockmonth = Number(data.month);
	clockday = Number(data.day);
	clocksecond = Number(data.second);
	clockminute = Number(data.minute);
	clockhour = Number(data.hour);
	
	$(function($) {
	 $('#dayclock').jclock();
	});			
}
$.getJSON("scripts/localid.php?idlanguage="+idlanguage+"&idcountry="+idcountry,localiddataresult);
//END LOCALID


//CONTACTO

function clearForm(all)
{
	$("#nameerror").html("");
	$("#emailerror").html("");
	$("#stateerror").html("");
	$("#cityerror").html("");
	$("#msgtypeerror").html("");
	$("#msgfielderror").html("");
	if(all)
	{
		$("#name").val("");
		$("#email").val("");
		document.getElementById("state").options.selectedIndex = 0;;
		$("#city").val("");
		document.getElementById("msgtype").options.selectedIndex = 0;
		$("#msgfield").val("");
	}
}

function sendMessage()
{
	
	$("#endcontactmsg").html("");
  //Se obtienen las variables del form y se eliminan los espacios en blanco a cada una;
  var name = $.trim($("input#name").val());
  var email = $.trim($("input#email").val());
  var state = document.getElementById("state").options.selectedIndex;
  var statename = $.trim($("select#state").val());
  var city = $.trim($("input#city").val());
  var msgtype = document.getElementById("msgtype").options.selectedIndex;
  var msgtypename = $.trim($("select#msgtype").val());
  var msgfield = $.trim($("textarea#msgfield").val());
  
  var filter = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
	var filtername =/^[a-zA-ZáéíóúÁÉÍÓÚnNAaEeOoçÇ]+(([\,\.\- ][a-zA-ZáéíóúÁÉÍÓÚnNAaEeOoçÇ ])?[a-zA-ZáéíóúÁÉÍÓÚnNAaEeOoçÇ ]*)*$/;

	// limpiar posibles mensajes de error anteriores
	clearForm(false);
	
	var error = false;
	
	//name
	if(name == ""){
		error = true;
		$("#nameerror").html("Debe ingresar su nombre");
	}
		if (filtername.test(name) == false && name != ""){
			error = true;
			$("#nameerror").html("El nombre que ha colocado es inválido");
	}

	//email
	if(email == ""){
		error = true;
		$("#emailerror").html("Debe ingresar su dirección de E-mail");
	}
	if (filter.test(email) == false && email != ""){
		error = true;
		$("#emailerror").html("Debe ingresar correctamente su dirección de E-mail");
	}

	//state
	if(state == 0){
		error = true;
		$("#stateerror").html("Debe seleccionar un estado");
	}

	//city
	if(city == ""){
		error = true;
		$("#cityerror").html("Debe indicar su ciudad");
	}
	if (filtername.test(city) == false && city != ""){
		error = true;
		$("#cityerror").html("La ciudad que ha ingresado es invlida");
	}

	if(msgtype == 0){
		error = true;
		$("#msgtypeerror").html("Debe seleccionar un tipo de mensaje");
	}

	if(msgfield == ""){
		error = true;
		$("#msgfielderror").html("Debe escribir un mensanje");
	}

	if(error == false){
		$("#send").hide();
		var data="name="+name+"&email="+email+"&state="+statename+"&city="+city+"&msgtype="+msgtypename+"&msgfield="+msgfield+"&action=sendComment";
	$.post("scripts/contact.php", data,sendMessageResult, "json");
	}
	
}

function sendMessageResult(data)
{
	clearForm(true);
	if(data.status)
	{
		$("#send").show();
		$("#endcontactmsg").html("Su mensaje fue enviado exitosamente");
		//alert("Su mensaje fue enviado exitosamente");
	}
	else
	{
		$("#send").show();
		$("#endcontactmsg").html("Su mensaje no fue enviado, Por favor intente más tarde");
	}
}
function clearMessage()
{
	// limpiar posibles mensajes de error anteriores
	clearForm(false);
	$("#msgcomment").val("");
}

//END CONTACT

//OFFICES
function showstate(id){
	var tab = String("table#t"+id);
	$("a").removeClass("officeselected");
	$("a#"+id).addClass("officeselected");
	$("table").hide();
	$(tab).show();
}


function showofficemap(map,img) {
	if(map == 1){
		$('#dialog').dialog('enable');
		$('#officemapimg').attr({src:img});
		$('#dialog').dialog('open');
	}else{
		$('#dialog').dialog('disable');
	}
	return false;
}

 function gooMap(x,y) {
	//if (GBrowserIsCompatible()) {		
		$('#dialogMap').dialog('open');		
		var map = new GMap2(document.getElementById("officemapdiv"));
		map.setMapType(G_HYBRID_MAP);
		map.setCenter(new GLatLng(x, y), 18);
		var point = new GLatLng(x, y);

		var baseIcon = new GIcon(G_DEFAULT_ICON, 'layouts/img/mapasTips.png');
		baseIcon.iconSize = new GSize(216, 68);
		baseIcon.iconAnchor = new GPoint(30, 65);

		map.addOverlay(new GMarker(point,baseIcon,true));
		map.setUIToDefault();
		//$('#dialogMap').dialog('enable');
	//}
}
//END OFFICES

//FONT SIZE SCRIPTS
$("#btnSFup").click(function(){
	$.get("scripts/fontsize.php", { size: "+"}, function(data){
		if(data == "true") window.location.reload();
	} );
});
$("#btnSFdown").click(function(){
	$.get("scripts/fontsize.php", { size: "-"}, function(data){
		if(data == "true") window.location.reload();	
	} );
});
//END FONT SIZE

/*** SEND TO FRIEND ***/
/*
try{
	// Dialog			
	$('#sendemail').dialog({
		modal: true,
		autoOpen: false,
		width: 750,
		height: 240
	});
	$('#sendemail').bind('dialogclose', function(event, ui) {
		$("span[id$='error']").html("");
	});

}catch(err){return;}
*/


function openSend(){
	
	$('#sendemail').dialog({
		modal: true,
		autoOpen: false,
		width: 750,
		height: 240
	});
	$('#sendemail').bind('dialogclose', function(event, ui) {
		$("span[id$='error']").html("");
	});

	$('#sendemail').dialog('open');
}

function validSend(usecclass){

	if(usecclass == undefined) usecclass = 0;

	$("span[id$='error']").html("");
	$("#sendrecomendbtn").attr("disabled","disabled");

	var errors = false;

	var sname = $.trim($("input#sendername").val());
	var email = $.trim($("input#recomendemail").val());
	var name = $.trim($("input#recomendname").val());
	var text = $.trim($("textarea#recomendtext").val());
	var filter = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
	var filtername =/^[a-zA-ZáéíóúÁÉÍÓÚñÑÃãÊêÕõçÇ]+(([\,\.\- ][a-zA-ZáéíóúÁÉÍÓÚñÑÃãÊêÕõçÇ ])?[a-zA-ZáéíóúÁÉÍÓÚñÑÃãÊêÕõçÇ ]*)*$/;

	if(email == ""){
		$("#recomendemailerror").html("Ingrese el email del destinatario");
		errors = true;
	}
	if(name == ""){
		$("#recomendnameerror").html("Ingrese el nombre del destinatario");
		errors = true;
	}
	if(filter.test(email) == false && email != ""){
		$("#recomendemailerror").html("Ingrese correctamente el email del destinatario");
		errors = true;
	}
	if(filtername.test(name) == false && name != ""){
		$("#recomendnameerror").html("Ingrese correctamente el nombre del destinatario");	
		errors = true; 
	}
	if(text == ""){
		$("#recomendmsgerror").html("Ingrese el mensaje");
		errors = true;
	}

	if(errors){
		$("#sendrecomendbtn").removeAttr("disabled"); 
	}else{

		var sname = $("input#sendername").val();
		if(sname == "") sname = "Remitente no especificado";

		var sub = $("#titSection").text();
		if(sub=="") sub = "Envío por email";

		$("#finalmsg").html("Enviando...");
		var tosend = {
			sendname : sname,	
			rcptemail : $("input#recomendemail").val(),
			rcptname : $("input#recomendname").val(),	
			text : $("textarea#recomendtext").val(),
			idcont : idcontainer,
			idcontclass : idcontainerclass,
			usecontainerclass: usecclass,
			urlstr: url,
			subject: sub,
			idtemplate: 5
		};

		$.post("scripts/sendtofriend.php", tosend, sendrecomend_result, "json");

	}
}

function sendrecomend_result(data){
	$("#sendrecomendbtn").removeAttr("disabled");	
	if(data.result==true){
		$("#finalmsg").html("Su mensaje ha sido enviado correctamente");
	} else {
	$("#finalmsg").html("Ha ocurrido un error enviando el mensaje, intente nuevamente");
	}
}

/*** END SEND TO FRIEND ***/
/*** PRINT ***/
function printPage(){
		
	var url = baseurl+"print.php?id="+idcontainer+"&idcontainerclass="+idcontainerclass;
	
	//caso noticias
	if(idcontainerclass == 15){
		window.print();
		return false;
	}
	
	if($.browser.msie){
		window.open(url); 		
	}else{	
		$('#printDiv').dialog({
			modal: true,
			autoOpen: false,
			width: 850,
			height: 500
		});
		$('#printDiv').bind('dialogclose', function(event, ui) {
			$("#printiframe").removeAttr("src");
		});
		$("#printiframe").attr("src",url);
		$('#printDiv').dialog('open');
	}
}

/*** END PRINT ***/
/*** PDF ***/

function printPdf(){

	if(idcontainerclass != 16){
	var url = baseurl+"fpdf/pospdf.php?idcontainerclass="+idcontainerclass;
	window.open(url);
	}
	else 
	{
	var urls = baseurl+"fpdf/tasaspdf.php?idcontainer="+idcontainer;
	window.open(urls);
	

}


}
