﻿// Francesc J. Miró 2011.

var $actual="";
var map;
var undefined;
var lat=38.594136; 
var lon=-0.672105;
var direccion = "<address><strong>Voralia</strong> <br />C/ Rei en Jaume I, 1 Castalla<br /></address>";


// ENLLAÇ AMB EL BLOG
var bLinks=0;
var bPortada=1;
var bOptica= 2;
var bAudio= 3;

// GESTIO DE COOKIES *************************
$.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // si s'ha especificat el nom i el valor, salvar cookie.
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // utilitzar el atribut 'expires' encara que no estࡳoportat per IE7
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // si sols s'ha especificat el nom, llavors llegir el cookie.
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var llengua = $.cookie("llengua");
if (llengua==null) {llengua='es';}; 


// DATES
function zeroPad(n, digits) {
	n = n.toString(); if(n.length>digits) n= n.substr(n.length-digits,digits);
	else {	while (n.length < digits) {	n = '0' + n;} }
	return n;
}

var mmToMonth = new Array("Ene", "Feb", "Mar", "Abr", "May", "Jun", "Jul", "Ago", "Sep", "Oct", "Nov", "Dic");
function showDate(date)
{
  var dt = new Date(date);
  var mm = mmToMonth[dt.getMonth()];
  return dt.getDate() + "-" + mm + "-" + zeroPad(dt.getFullYear(),2) + " " + zeroPad(dt.getHours(),2) + ":" + zeroPad(dt.getMinutes(),2);
}
function abrir(direccion, ancho, alto, izquierda, arriba, sustituir){
	var opciones =	"fullscreen=0, toolbar=0, location= 0. status= 0, menubar= 0 ,scrollbars=1, resizable=1" +
		",width=" + ancho +
		",height=" + alto;
	var ventana = window.open(direccion,"Comentario",opciones,sustituir);
	if (window.focus) {ventana.focus()}
	return false;	
}  

function setFavicon() {
  var link = $('link[type="image/x-icon"]').remove().attr("href");
  $('<link href="'+ link +'" rel="shortcut icon" type="image/x-icon" />').appendTo('head');
}

function actHash() {
	if(window.location.hash!=$actual) {
		window.location.hash=$actual;
		setFavicon();
	}
}


//   FORMULARIS *****************************

function checkForm(form) {
    $('.error', form).hide();  
	var resp = '';
	$('input, textarea',form).each(function(i) {
		var req=$(this).hasClass('req');
		var esEmail=$(this).hasClass('email');
		var esFecha=$(this).hasClass('fecha');
		var esNum=$(this).hasClass('num');
		var valor=$(this).val();
		var nom=$(this).attr('name');
		var error=false;
		if(req) {
			if (valor == "") { error=true;}
			if (esEmail) { if( !valor.match("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$"))  {error = true;} }
			if (esFecha) { if( !valor.match("/\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/")) {error= true;} }
		}
		if (error) {
			$("label#"+ nom +"_error", form).show();  
			this.focus(); 
			resp='';
			return false;  
		}
		else {	resp += '&' + nom + "=" + valor; }
	});
	if (resp) { return resp.substr(1);}
}
		



// IMPORTACIÓ DE TWITTER *************************
(function( $ ){
	$.fn.twitter = function (twitterUser, tweets) { 
		var eldiv=this;
		$.getJSON("http://twitter.com/status/user_timeline/"+twitterUser+".json?count=" + (tweets*2) +"&callback=?",function(json){
			html = "";
			var urlregex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;
			var userregex = /(\@([-A-Z0-9+&\/%?=~_|!:,.;]*))/gi;
			var hashtagregex = /(\#([-A-Z0-9+&\/%?=~_|!:,.;]*))/gi;
			var count = 0;
			for (i=0;i<json.length;i++)    {
				if (json[i].in_reply_to_screen_name==null)      {
					html += "<div><p class='text'>" + json[i].text.replace(urlregex,"<a class='url' href='$1' rel='nofollow'>$1</a>").replace(userregex,"<a class='user' href='http://twitter.com/$2' rel='nofollow'>$1</a>").replace(hashtagregex,"<a class='hashtag' href='http://twitter.com/#search?q=$1' rel='nofollow'>$1</a>") + "</p>";
					html += "<p><a class='rt' href='http://twitter.com/home?status=RT @"+twitterUser+" "+json[i].text+"' rel='nofollow'>[ReTweet]</a> ";
					html += "<a class='reply' href='http://twitter.com/home?status=@"+twitterUser+" &amp;in_reply_to_status_id=" + json[i].id + "&amp;in_reply_to="+twitterUser+"' rel='nofollow'>[Responder]</a></p></div>";
					count++;
				}
				if (count >= tweets) break;
			}
			// incluim el html dins del div que hem passat
			$(html).appendTo(eldiv);
	$("#twitter").cycle({ 	 fx:'fade', timeout: 10000, delay:  -2000 });
		})
	}
})( jQuery );

// conexió amb fasegurabuc *************************
(function( $ ){
	$.fn.facebook = function () { 
		var eldiv=this;
		jQuery.ajax({
			 type: "GET",
			 url: "http://connect.facebook.net/es_ES/all.js#xfbml=1",
			 dataType: "script",
			 cache: true,
			 success: function(){
				eldiv.append('<fb:like class="fb_edge_widget_with_comment fb_iframe_widget" font="tahoma" show_faces="false" width="200" layout="button_count" send="true" href="http://www.voralia.es"></fb:like>');
				FB.init({ appId:'285249591805', secret: 'd29952a159842d4b4facec5c27ad45c7',cookie:true,  status:false, xfbml:true, width:"200px" });
			 }
		});
	}
})( jQuery );

// IMPORTACIÓ DE BLOGGER *************************
(function( $ ){
	$.fn.blogspot = function (cat, coments) { 
	    var actPanel=this;
		var eldiv=this.find("#posts");
		var index= this.find('ul.postsindex');
        var paras = { alt : 'json-in-script', category: cat  };


		function Comentaris(div, idBlog, idPost) {
			var html = '<a onclick="abrir(';
			html += "'https://www.blogger.com/comment.g?blogID="+ idBlog +"&amp;postID=" + idPost +"',750,800,100,100,1);";
			html += '" href="#" class="comComentar">Comenta</a>';
			html +='<h4>comentarios</h4>';
			div.empty().append(html);
			html='';
			$.getJSON("http://www.blogger.com/feeds/"+ idBlog+"/"+idPost+"/comments/default?alt=json-in-script&callback=?", function(data) {
				var feed = data.feed;
				var coms = feed.entry || [];
				if (coms.length==0) { html='Aun no hay comentarios'; }
				else {
				for (var j = 0; j < coms.length; ++j) {
					var c = coms[j];
					html += '<div class="comentari"><div class="comCapsal"><span class="comFecha">'+ showDate(c.published.$t) +'</span>';
					var autor=c.author[0].name.$t;
					if(autor=='Anonymous') autor='alguien..';
					html += '<span class="comAutor">' +autor+ '</span>';
					html += '</div><p>' + c.content.$t +'</p></div>';
				}}
				div.append(html);
			});
			
		}
		
		jQuery.ajax({
			url: 'http://blog.voralia.es/feeds/posts/default', 
			type: 'get',
            dataType: "jsonp",
            data: paras,
			cache:true,
 			success:function(data) {
				var feed = data.feed;
				var entries = feed.entry || [];
			    eldiv.empty();
				if (index) index.empty(); 
				for (var i = 0; i < entries.length; ++i) {
					var entry = entries[i];
					var title = entry.title.$t;
					var posturl, idPost, idBlog;
					for (var k = 0; k < entry.link.length; k++) {
						if (entry.link[k].rel == 'edit') {
							posturl = entry.link[k].href;
							var ss=posturl.split("/");
							idBlog=ss[4];
							idPost=ss[7];
							break;
						}
					}
					var id= entry.id.$t;
					if(coments) {
						index.append('<li><a  href="#'+$actual+'" ' + ((i==0)?' class="actiu"':"") + 'post="#p'+idPost+'">'+title+'</a></li>');
						eldiv.append('<div class="post' + ((i==0)?" actiu":"") +'" id="p'+idPost+'"><div id="c' + idPost+'" class="comentaris"></div><h3>'+title+'</h3>'+ entry.content.$t+'</div>');
						Comentaris($("#c"+idPost),idBlog,idPost);
						$("a",index).click(function(){
							var este=this;
							var nou=$(this).attr('post');

							$(".actiu", eldiv).fadeOut("fast", function() {  
								$(".actiu", index).removeClass('actiu');
								$(nou).addClass('actiu').fadeIn("fast");
								$(this).removeClass('actiu');
								$(este).addClass('actiu');
								actHash();
							});
						});
					}
					else {	eldiv.append('<div><h3>'+title+'</h3>'+ entry.content.$t+'</div>');	}
					AplicaUI(eldiv);
				}
			 }
		 });
	},
	$.IpCliente = function() {
		$.getJSON("http://jsonip.appspot.com?callback=?", function(data) {	this.append(data)});
		return this;
	}
})( jQuery );

//Tooltips
(function( $ ){
	$.fn.tips = function () { 
		var eldiv=this;
		eldiv.hover(
			function(){	$(this).find('.tip').show(); 	}, 
			function() {	$(this).find('.tip').hide();}
		).mousemove(function(e) {
			//agafa coordenades
			var mousex = e.pageX + 20;
			var mousey = e.pageY + 20;
			//calcula ample i llarc
			var tipWidth = $(this).find('.tip').width(); 
			var tipHeight = $(this).find('.tip').height();
				//Calcula distáncia fins la part dreta del contenidor
			var tipVisX = $(window).width() - (mousex + tipWidth);
			var tipVisY = $(window).height() - (mousey + tipHeight);
			if ( tipVisX < 20 ) { //En cas de que el ample siga mes gran que el del contenidor
				mousex = e.pageX - tipWidth - 20;
				$(this).find('.tip').css({  top: mousey, left: mousex });
			} 
			if ( tipVisY < 20 ) { 
				mousey = e.pageY - tipHeight - 20;
				$(this).find('.tip').css({  top: mousey, left: mousex });
			} else {
				$(this).find('.tip').css({  top: mousey, left: mousex });
			}
		});
	}
})( jQuery );


function AplicaUI(panel) {
	if(panel) {
		/*$('.botodialeg', panel).click(function(){$('#dialeg').dialog('open');return false;});
		$('.dialeg', panel).dialog({autoOpen: false,width: 600,	buttons: {"Aceptar": function() { $(this).dialog("close"); }, 	"Cancelar": function() { $(this).dialog("close"); }}});
		$('.dialog_link, ul.icons li', panel).hover(function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); });
		$('.tabs', panel).tabs();
		*/
		 
		$('div.acordeon', panel).accordion({ header: "h2" });
		$("button,  input:submit", panel).button({ icons: {primary:'ui-icon-arrow-1-e'}});
    	$(".infotip", panel).tips();
		if(llengua!='es') { $('*',panel).translate('es', llengua,  { fromOriginal: true, not:'#logo' }); }	
	}
	return false
}



$(function () {

	$('.error').hide();  
	


	var $contactar = $( "#fcontacte" ).dialog({
		autoOpen: false,
		modal: true,
		title: "Formulario de contacto",
		width: "650px",
		buttons: {
			Enviar: function() { 
				var f=$('form', $contactar);
				var paras= checkForm(f);
				if (paras) {
					$('#opcions', $contactar).empty().append(
						'<input type="hidden" value="info@voralia.es" name="recipient">' +
						'<input type="hidden" value="Nuevo cliente registrado en Voralia.es" name="subject">'+
						'<input type="hidden" value="http://www.voralia.es/index.html#OK" name="redirect">'+
						'<input type="hidden" value="http://www.voralia.es/index.html#NOOK" name="missing_fields_redirect">');
					f.submit();
					$( this ).dialog( "close" );
				}
			},
			Cancelar: function() {	$( this ).dialog( "close" );}
		},
		open: function() { $("#fcnombre").focus();	},
		close: function() { $('form', $contactar).reset();}
	});
	var $promo = $( "#fpromo" ).dialog({
		autoOpen: false,
		modal: true,
		title: "Rellena el formulario y te enviamos tu CHEQUE DESCUENTO",
		width: "650px",
		buttons: {
			Enviar: function() {	
				var paras= checkForm($('form', $promo));
				if (paras) {
					$('#opcions', $promo).empty().append(
						'<input type="hidden" value="info@voralia.es" name="recipient">' +
						'<input type="hidden" value="Nuevo cliente registrado para Promociones en Voralia.es" name="subject">'+
						'<input type="hidden" value="http://www.voralia.es/index.html#OK" name="redirect">'+
						'<input type="hidden" value="http://www.voralia.es/index.html#NOOK" name="missing_fields_redirect">');
					$('form', $promo).submit();
					$( this ).dialog( "close" );
				}
			},
			Cancelar: function() {	$( this ).dialog( "close" );}
		},
		open: function() { $("#fpnombre").focus();	},
		close: function() { $('form', $promo).reset();}
	});
	var $vista = $( "#fvista" ).dialog({
		autoOpen: false,
		modal: true,
		title: "Cita para revisión de la vista",
		width: "650px",
		buttons: {
			Enviar: function() {	
				var paras= checkForm($('form', $vista));
				if (paras) {
					$('#opcions', $vista).empty().append(
						'<input type="hidden" value="info@voralia.es" name="recipient">' +
						'<input type="hidden" value="Petición de cita para revisión de vista/audición" name="subject">'+
						'<input type="hidden" value="http://www.voralia.es/index.html#OK" name="redirect">'+
						'<input type="hidden" value="http://www.voralia.es/index.html#NOOK" name="missing_fields_redirect">');
					$('form', $vista).submit();
					$( this ).dialog( "close" );
				}
			},
			Cancelar: function() {	$( this ).dialog( "close" );}
		},
		open: function() { $("#fpnombre", this).focus();	},
		close: function() { $('form', $vista).reset();}
	});

    $(".fcontacto").click(function(){ $contactar.dialog('open');return false;});
    $(".fpromo").click(function(){ $promo.dialog('open');return false;});
    $(".fvista").click(function(){ $vista.dialog('open');return false;});
	
	
// ******* MENU I PAGINES ********
	var $menu = $("#menu").tabs({
		fx: {opacity: "toggle",duration:300},
		load: function(event, ui) { 
			AplicaUI(ui.panel); 
		},
		show: function(event, ui) {
			$actual= ui.panel.id;
			//actHash();
			switch(ui.index) {
				case 0: $('.content',ui.panel).blogspot('portada',false);	break;	
				case 1: $('.content',ui.panel).blogspot('optica',false);	break;		
				case 2: $('.content',ui.panel).blogspot('audio',false);	break;		
				case 3: $('.content',ui.panel).blogspot('promociones',false);	break;		
				case 5: $(ui.panel).blogspot('blog',true);	break;		
			}
		},
		select: function() {}
	});

    //  NAVEGACIO
    var AnarAID =window.location.hash.substr(1);
	if (AnarAID) {
		switch (AnarAID) {
			case 'OK': alert('Datos enviados correctamente'); break;
			case 'NOOK': alert ('Eror al enviar'); break;
			default:
				var listItem = document.getElementById('M'+ AnarAID);
				$menu.tabs('select', $("#menu li").index(listItem));
		}
	 }

	 //  TRADUCCIO ********
	$('#lenguatges img')
		.click(function(){ 
			$('#lenguatges img').removeClass('lactiu'); 
			llengua=this.name;
			$.cookie("llengua",llengua);
			if (llengua != 'es') {$('body').translate('es', this.name,  { fromOriginal: true, not:'#logo' });} 
			else { window.location.reload();}
			$(this).addClass('lactiu');
		})	
		.hover(	function () {$(this).animate({ opacity: 1}, 500 );}, function () {$(this).animate({ opacity: 0.4}, 600 );});
	
	$(".boto").button();
	$("img.reflejar").reflect({height: 0.2, opacity: 0.3});

	//  IMATGES LINKADES
	$("#banners img:visible")
		.wrap('<div class="marc"></div>');
		//.hover( function() { $(this).animate({ 
	$("#banners .tab").click(function(){ $menu.tabs('select', $(this).attr('tab')-1 );});
	
	$("#twitter").twitter("voraliaoptics",7);
	$("#facebook").facebook();
	
	$(".infotip, .imgtip").tips();
	$("#links a, #footer a").each(function(index) {
        if($(this).attr('href').substr(0,1)=='#') {
		   $(this).click(function() {		
				var listItem = document.getElementById('M'+ $(this).attr('href').substr(1));
				$menu.tabs('select', $("#menu li").index(listItem));
			});
		}
	});

	$.getScript('http://jquery-translate.googlecode.com/files/jquery.translate-1.3.9.min.js', function() {
		if(llengua!='es') {
			$('#lenguatges img').removeClass('lactiu'); 
			$('body').translate('es', llengua,  { fromOriginal: true, not:'#logo' }); 
			$('#lenguatges img[name*= "'+llengua+'"]').addClass('lactiu');
		}			
	});

	//mapa
	if (GBrowserIsCompatible()) {
			var icon = new GIcon("favicon.ico");
			var marcador = new GMarker(new GLatLng(lat, lon));
			icon.infoWindowAnchor = new GPoint(0,0);
			GEvent.addListener(marcador, "click", function(){marcador.openInfoWindowHtml(direccion);});
			map = new GMap2(document.getElementById("mapa"));
			map.setCenter(new GLatLng(lat,  lon), 18);
			map.setMapType(G_SATELLITE_MAP);
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());
			map.addOverlay(marcador);
			marcador.openInfoWindowHtml(direccion);
	}
	
});
	
