/*$('#tooltipitem').tooltip({ 
    bodyHandler: function() { 
    	return $($(this).attr("alt")).html() + '. ' + $($(this).attr("longdesc")).html(); 
	}, 
	showURL: false 
});*/

$(document).ready( function(){
  $('ul.sf-menu').superfish();
  $('.qtip_item').qtip({ style: { name: 'cream', tip: true, show: 'mouseover', hide: 'mouseout' },position: { target: 'mouse' ,adjust: { x: 10, y: 10 }}});
  $('.qtip_android').qtip({
	  content: '<img src="/images/qrandroid.png" alt="Metroo QR Code" />',
	  position: {target: 'mouse',adjust: { x: 10, y: 10 }}	      
   });
  $("#pa_mtr_update_update_text").keyup(function() {
	   mostrarCaracteresRestantes();
  });
});

function showMoreComments(label, lastComment, lastcommentnumber, lastcommentdtreviewed)
{
  $('#view_more_comments_'+lastComment).css("display", "none"); 
  $('#div_more_comments_'+lastComment).load("/ajax/getcomments"+"/"+label+"/"+lastComment+"/"+lastcommentnumber + '?lastcommentdtreviewed=' + lastcommentdtreviewed);
}

function rateImg(rating)  
{
	document.getElementById('newcomment_therate').value = rating;
	rating = rating * 25;
	document.getElementById('current-rating').style.width = rating+'px';	
}

function makeFan(business_id, isfan, business_url, business_name, fb_id)
{
	var comment = '';
	var url = '/metroo/ajax-makefan.php?business_id=' + business_id + '&isfan=' + isfan;
	if( isfan == 1 ) {
		$('#ilikebutton').fadeOut();
		$('#action-favourite').fadeIn();
	}
	else {
		$('#action-favourite').fadeOut();
		$('#ilikebutton').fadeIn();
	}
	$.get(url);
}

function showCityForm(provinceid, city_id) {
	if(provinceid > 0)
	{
		$('#cityInputInner').load('/ajax/getcityselect/' + provinceid + '?createBusiness=1&selected=' + city_id);
	}
	else {
		$('#cityInput').css("display", "none"); 
		$('#cityInput').html = '';
	}
}

function htmlentities (string, quote_style) {
    var histogram = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (histogram = get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    
    for (symbol in histogram) {
        entity = histogram[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}
function get_html_translation_table(table, quote_style) {
    
    var entities = {}, histogram = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    useTable      = (table ? table.toUpperCase() : 'HTML_SPECIALCHARS');
    useQuoteStyle = (quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT');
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
    // Map numbers to strings for compatibilty with PHP constants
    if (!isNaN(useTable)) {
        useTable = constMappingTable[useTable];
    }
    if (!isNaN(useQuoteStyle)) {
        useQuoteStyle = constMappingQuoteStyle[useQuoteStyle];
    }
    
    if (useQuoteStyle != 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
 
    if (useQuoteStyle == 'ENT_QUOTES') {
        entities['39'] = '&#039;';
    }
 
    if (useTable == 'HTML_SPECIALCHARS') {
        // ascii decimals for better compatibility
        entities['38'] = '&amp;';
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    } else if (useTable == 'HTML_ENTITIES') {
        // ascii decimals for better compatibility
      entities['38']  = '&amp;';
      entities['60']  = '&lt;';
      entities['62']  = '&gt;';
      entities['160'] = '&nbsp;';
      entities['161'] = '&iexcl;';
      entities['162'] = '&cent;';
      entities['163'] = '&pound;';
      entities['164'] = '&curren;';
      entities['165'] = '&yen;';
      entities['166'] = '&brvbar;';
      entities['167'] = '&sect;';
      entities['168'] = '&uml;';
      entities['169'] = '&copy;';
      entities['170'] = '&ordf;';
      entities['171'] = '&laquo;';
      entities['172'] = '&not;';
      entities['173'] = '&shy;';
      entities['174'] = '&reg;';
      entities['175'] = '&macr;';
      entities['176'] = '&deg;';
      entities['177'] = '&plusmn;';
      entities['178'] = '&sup2;';
      entities['179'] = '&sup3;';
      entities['180'] = '&acute;';
      entities['181'] = '&micro;';
      entities['182'] = '&para;';
      entities['183'] = '&middot;';
      entities['184'] = '&cedil;';
      entities['185'] = '&sup1;';
      entities['186'] = '&ordm;';
      entities['187'] = '&raquo;';
      entities['188'] = '&frac14;';
      entities['189'] = '&frac12;';
      entities['190'] = '&frac34;';
      entities['191'] = '&iquest;';
      entities['192'] = '&Agrave;';
      entities['193'] = '&Aacute;';
      entities['194'] = '&Acirc;';
      entities['195'] = '&Atilde;';
      entities['196'] = '&Auml;';
      entities['197'] = '&Aring;';
      entities['198'] = '&AElig;';
      entities['199'] = '&Ccedil;';
      entities['200'] = '&Egrave;';
      entities['201'] = '&Eacute;';
      entities['202'] = '&Ecirc;';
      entities['203'] = '&Euml;';
      entities['204'] = '&Igrave;';
      entities['205'] = '&Iacute;';
      entities['206'] = '&Icirc;';
      entities['207'] = '&Iuml;';
      entities['208'] = '&ETH;';
      entities['209'] = '&Ntilde;';
      entities['210'] = '&Ograve;';
      entities['211'] = '&Oacute;';
      entities['212'] = '&Ocirc;';
      entities['213'] = '&Otilde;';
      entities['214'] = '&Ouml;';
      entities['215'] = '&times;';
      entities['216'] = '&Oslash;';
      entities['217'] = '&Ugrave;';
      entities['218'] = '&Uacute;';
      entities['219'] = '&Ucirc;';
      entities['220'] = '&Uuml;';
      entities['221'] = '&Yacute;';
      entities['222'] = '&THORN;';
      entities['223'] = '&szlig;';
      entities['224'] = '&agrave;';
      entities['225'] = '&aacute;';
      entities['226'] = '&acirc;';
      entities['227'] = '&atilde;';
      entities['228'] = '&auml;';
      entities['229'] = '&aring;';
      entities['230'] = '&aelig;';
      entities['231'] = '&ccedil;';
      entities['232'] = '&egrave;';
      entities['233'] = '&eacute;';
      entities['234'] = '&ecirc;';
      entities['235'] = '&euml;';
      entities['236'] = '&igrave;';
      entities['237'] = '&iacute;';
      entities['238'] = '&icirc;';
      entities['239'] = '&iuml;';
      entities['240'] = '&eth;';
      entities['241'] = '&ntilde;';
      entities['242'] = '&ograve;';
      entities['243'] = '&oacute;';
      entities['244'] = '&ocirc;';
      entities['245'] = '&otilde;';
      entities['246'] = '&ouml;';
      entities['247'] = '&divide;';
      entities['248'] = '&oslash;';
      entities['249'] = '&ugrave;';
      entities['250'] = '&uacute;';
      entities['251'] = '&ucirc;';
      entities['252'] = '&uuml;';
      entities['253'] = '&yacute;';
      entities['254'] = '&thorn;';
      entities['255'] = '&yuml;';
    } else {
        throw Error("Table: "+useTable+' not supported');
        return false;
    }
    
    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal)
        histogram[symbol] = entities[decimal];
    }
    
    return histogram;
}

function twitthis(label) {
	var leftpos = (window.screen.width - 860) / 2;
	var toppos = (window.screen.height - 420) / 2;
	window.open("http://metroo.es/twitthis/"+encodeURIComponent(label), "Comparte en Twitter - Metroo", "width=860, height=420, top="+toppos+", left="+leftpos+",location, status, scrollbars, resizable");
}

function newinput(type) {
	if( type == 'video' ) {
		var eDIV = document.createElement("div");
		elem = document.createElement('strong');
		elem.appendChild(document.createTextNode('URL vídeo:'));
		eDIV.appendChild(elem);
		eDIV.appendChild(document.createTextNode(' '));
		elem = document.createElement('input');
		elem.type='text';
		elem.name="newcomment[thevideo][]";
		elem.className="video";
		eDIV.appendChild(elem);
		document.getElementById('videoform').appendChild(eDIV);
	}
	else if (type == 'photo') {
		var eDIV = document.createElement("div");
		elem = document.createElement('strong');
		elem.appendChild(document.createTextNode('Foto:'));
		eDIV.appendChild(elem);
		eDIV.appendChild(document.createTextNode(' '));
		elem = document.createElement('input');
		elem.type='file';
		elem.name="newcomment[thephoto][]";
		elem.setAttribute("size","36");
		eDIV.appendChild(elem);
		document.getElementById('photoform').appendChild(eDIV);
	}
	else if( type == 'phototop' ) {
		var eDIV = document.createElement("div");
		elem = document.createElement('strong');
		elem.appendChild(document.createTextNode('Foto:'));
		eDIV.appendChild(elem);
		eDIV.appendChild(document.createTextNode(' '));
		elem = document.createElement('input');
		elem.type='file';
		elem.name="newcomment[thephoto][]";
		elem.setAttribute("size","36");
		eDIV.appendChild(elem);
		document.getElementById('photoformtop').appendChild(eDIV);
	}
	else if( type == 'videotop' ) {
		var eDIV = document.createElement("div");
		elem = document.createElement('strong');
		elem.appendChild(document.createTextNode('URL vídeo:'));
		eDIV.appendChild(elem);
		eDIV.appendChild(document.createTextNode(' '));
		elem = document.createElement('input');
		elem.type='text';
		elem.name="newcomment[thevideo][]";
		elem.className="video";
		eDIV.appendChild(elem);
		document.getElementById('videoformtop').appendChild(eDIV);
	}
}
function showHomeCityForm( province ) {
	if( province > 0 ) {
		var url = '/metroo/mtr-home-city-selector.php?province=' + province;	
		$('#cityselector').load(url); 
	}
	else {
		$('#cityselector').html = '<select id="city" name="city" onFocus="this.style.backgroundColor=\'#FFFF99\';" onBlur="this.style.backgroundColor=\'white\';"><option value="0">Elige ciudad...</option></select>';
	}
}

function goCityHome(cityDiv) {
	
	if(cityDiv == null)
		cityDiv = 'city';
	
	if( $(cityDiv).value != '' ) {
		document.location.href='http://' + $(cityDiv).value + '.metroo.es/';
	}
}

function errorUltimaActividadMiCiudad(cityDiv) {
	
	if(cityDiv == null)
		cityDiv = 'city';
	
	if(document.getElementById("province").value == 0)
	{
		alert(variableTextoErrorProvincia);
		return false;
	}
	if(document.getElementById(cityDiv).value == 0)
	{
		alert(variableTextoErrorCiudad);
		return false;
	}
}

function clickAndExpand(jqueryitem){
	$(jqueryitem).delay(200).slideToggle();
}

function mostrarCaracteresRestantes(){	
	   $('#charsLeft').show();
	   var numCaracteres = 255-$('#pa_mtr_update_update_text').val().length;
	   $('#charsLeft').text(numCaracteres + '/255');
	   if (numCaracteres<0){
		   $('#charsLeft').show();
		   $('#charsLeft').css('color', 'red');
		   $('#btnSubmitComment').css('background-image','url(/images/botSmallDisabled.png)');
		   $('#btnSubmitComment').attr('disabled','disabled');
		}else if($('#pa_mtr_update_update_text').val().length==0){
			$('#charsLeft').hide();
			$('#btnSubmitComment').css('background-image','url(/images/botSmallDisabled.png)');
			$('#btnSubmitComment').attr('disabled','disabled');
		}else{
			$('#charsLeft').show();
			$('#btnSubmitComment').css('background-image','url(/images/botSmall.png)');
			$('#btnSubmitComment').removeAttr('disabled');
			$('#charsLeft').css('color', '#506489');
		}
}

function clickLink(numero)
{	
/*	if(numero==1){
		$(".linkCity2").css({ color: "grey"});
		$(".linkCity1").css({ color: "#506489"});
	}else{
		$(".linkCity1").css({ color: "grey"});
		$(".linkCity2").css({ color: "#506489"});
	}*/
}

function getCitiesSelectByProvince (provinceid, field, url, fieldaction, fieldname) {
	$('#loadimage').show('fast', function() {
		if(field == null)
			field ='selCity';
		if(url == null)
			url ='/ajax/getcitiesselect/';
		var totalurl = url + provinceid;
		if(fieldaction != null && fieldname != null)
		{
			totalurl = totalurl + '?fieldaction=' + fieldaction + '&fieldname=' + fieldname;
		}
		$('#'+field).removeAttr("disabled").load(totalurl, function() {
			$('#loadimage').hide('slow');
		});		
	});

}

function redirectLocation(city){
	if(city!=''){		
		$('#loadimage').show('fast', function() {
			document.location.href='http://' + city + '.metroo.es/';
		});
	}
}

function mustBeLogged()
{
	$('#must_be_logged').css('display', 'block');
}

function metrooLoginFb()
{
	FB.login(function(response) {
		  if (response.session) {
		    window.location.href = unescape(window.location);
		  } else {
		    // user is not logged in
		  }
		}, {perms:'publish_stream,offline_access'});
}

function updateCityMetrooCount(city)
{
  var url = '/ajax/updateMetrooCount?city=' + city;
  $('#metroocount').load(url);
}

function updateMetrooCount(city)
{
  var url = '/ajax/updateMetrooCount';
  $('#metroocount').load(url);
  $('#totalmetroocount').load(url);
    url = '/ajax/updateMetrooCount?city=' + city;
  $('#metroocount_' + city).load(url);
}

/* Shadowbox*/
Shadowbox.init({
	  language: 'es',
	  players:  ['img', 'html', 'iframe', 'qt', 'wmp', 'swf', 'flv']
	});
	function globalSelectCity() {

	    // open a welcome message as soon as the window loads
	    Shadowbox.open({
	    	content:    '<table id="choose-city"><tr><td width="200"><a href="http://madrid.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'madrid\', \'elige Madrid en la nube de ciudades\');">Madrid</a></td><td width="200"><a href="http://murcia.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'murcia\', \'elige Murcia en la nube de ciudades\');">Murcia</a></td></tr><tr><td><a href="http://barcelona.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'barcelona\', \'elige Barcelona en la nube de ciudades\');">Barcelona</a></td><td><a href="http://valencia.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'valencia\', \'elige Valencia en la nube de ciudades\');">Valencia</a></td></tr><tr><td><a href="http://bilbao.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'bilbao\', \'elige Bilbao en la nube de ciudades\');">Bilbao</a></td><td><a href="http://malaga.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'malaga\', \'elige Málaga en la nube de ciudades\');">Málaga</a></td></tr><tr><td><a href="http://las-palmas.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'las palmas\', \'elige Las Palmas en la nube de ciudades\');">Las Palmas</a></td><td><a href="http://palma.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'mallorca\', \'elige Mallorca en la nube de ciudades\');">Mallorca</a></td></tr><tr><td width="200"><a href="http://sevilla.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'sevilla\', \'elige Sevilla en la nube de ciudades\');">Sevilla</a></td><td width="200"><a href="http://zaragoza.metroo.es/" onclick="analyticsTracker(\'elige ciudad\', \'zaragoza\', \'elige Zaragoza en la nube de ciudades\');">Zaragoza</a></td></tr><tr><td colspan="2" align="right"><font size="2px"><a href="http://metroo.es/provinceslist" onclick="analyticsTracker(\'elige ciudad\', \'ver todas\', \'elige ver todas en la nube de ciudades\');">Ver todas</a></font></td></tr></table></div>',
	        player:     'html',
	        title:      'Elige ciudad',
	        height:     '165'
	    });

	}
/* End Shadowbox*/
	
function analyticsTracker(category, action, label)
{	
	if(pageTracker){
		pageTracker._trackEvent(category, action, label);
	}else{	
		/*var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
		
		try {
			  var pageTracker = _gat._getTracker("UA-12345678-9");
			  pageTracker._trackPageview();
			} catch(err) {}
			
		pageTracker._trackEvent(category, action, label);
			*/
	}
}

function saveFbOptions(userlabel, needpermissions)
{
	$('#fboptions_save').attr("disabled", true);
	
	if(needpermissions == 'need')
	{
		FB.login(function(response) {
			  if (response.session) {
				  finishSavingFbOptions(userlabel);
			  }
		}, {perms:'publish_stream,offline_access'});
	}
	else
	{
		finishSavingFbOptions(userlabel);
	}
	
}

function finishSavingFbOptions(userlabel)
{
	$.post("/ajax/savefboptions/" + userlabel, 
			{ comment: $('#fboptions_comment:checked').val(), fan: $('#fboptions_fan:checked').val(), insert: $('#fboptions_insert:checked').val(), badge: $('#fboptions_badge:checked').val(), checkin: $('#fboptions_checkin:checked').val() },
			function(){
				$('#fboptions_message').fadeIn('slow', function(){
					setTimeout("$('#fboptions_message').fadeOut('slow', function(){$('#fboptions_save').attr('disabled', false);});", 2000);
				});
				
			}
	);
}

function changeFacebook()
{
  if($('#to_facebook').val() == 1)
  {
    $('#to_facebook_button_1').removeClass('facebook_follwo').addClass('facebook_nofollwo');
    $('#to_facebook_button_2').removeClass('facebook_follwo').addClass('facebook_nofollwo');
    $('#to_facebook').val(0);
  }
  else
  {
    $('#to_facebook_button_1').removeClass('facebook_nofollwo').addClass('facebook_follwo');
    $('#to_facebook_button_2').removeClass('facebook_nofollwo').addClass('facebook_follwo');
    $('#to_facebook').val(1);
  }
}

function changeTwitter()
{
  if($('#to_twitter').val() == 1)
  {
    $('#to_twitter_button_1').removeClass('twitter_follwo').addClass('twitter_nofollwo');
    $('#to_twitter_button_2').removeClass('twitter_follwo').addClass('twitter_nofollwo');
    $('#to_twitter').val(0);
  }
  else
  {
    $('#to_twitter_button_1').removeClass('twitter_nofollwo').addClass('twitter_follwo');
    $('#to_twitter_button_2').removeClass('twitter_nofollwo').addClass('twitter_follwo');
    $('#to_twitter').val(1);
  }
}

function changeSubcategories(parent)
{
	$('#subcategories_select').load('/ajax/changesubcategories/' + parent, function(){
		 $("#subcategories_select select").uniform();
	});
}

function changeFormByCategory(category)
{
	if(category == 11015)
	{
		$('#divPunto').hide();
		$('#divGasolinera').hide();
		$('#divRadar').hide();
		$('#divPlaya').show();
	}
	else if(category == 14010)
	{
		$('#divPlaya').hide();
		$('#divPunto').hide();
		$('#divGasolinera').hide();
		$('#divRadar').show();
	}
	else if(category == 14020)
	{
		$('#divPlaya').hide();
		$('#divPunto').hide();
		$('#divRadar').hide();
		$('#divGasolinera').show();
	} 
	else
	{
		$('#divPlaya').hide();
		$('#divGasolinera').hide();
		$('#divRadar').hide();
		$('#divPunto').show();
	}
}