try
{
  google.load("language", "1");
}
catch(exception)
{
//no need to do anything
}
//evitar atras en la pagina de inicio

//menu behavior
jQuery(document).ready(function(){
  bindIE9UploaderAction();
  setInputsBehavior();
  bindFacebox();
  bindAccordionList();
  bindTabs();
  jQuery(document).bind('reveal.facebox', function(){
    //must rebind the tabs since we'll use them inside the facebox
    bindTabs();
    unbindForceredirect();
  });
  unbindForceredirect();
})

function unbindForceredirect()
{
  $('.linkforceredirect').each(function(){
    $(this).unbind('click');
    if ($(this).hasClass('trackablebanner'))
    {
      $(this).bind('click',function(event){
        var fullurl = $(this).attr('fullurl');
        var routename = $(this).attr('routename');
        var tourl = $(this).attr('href');
        
        $.ajax({
          type: 'POST',
          dataType: "html",
          url: '/index.php/Home/saveClick',
          async: false,
          data: ({
            urlfull:fullurl,
            nameroute:routename,
            urlto:tourl
          }),
          success: function(data) 
          {
            
            return true;
          }
        });
      });
    }
  });
}

$('ul.mainMenu').ready(function(){
  setupMenuBehavior();
  setupsmartSearchBehavior();
});

$('.leftContainer').ready(function(){
  setSideMenuBehavior();
});

$('.smartleftContainer').ready(function(){
    setSmartSideMenuBehavior();
});

function bindIE9UploaderAction()
{
  return true;
}

//sets up the menu opening
function setupMenuBehavior()
{
  jQuery('ul.mainMenu').find('li').each(function(){
    if (jQuery(this).children('ul').length > 0)
    {
      //the menu has children
      jQuery(this).find('span').append('<img src="/images/arrowDown.gif"/>');
      jQuery(this).hover(function(){
        jQuery(this).find('ul').show('fast');
      }, function(e){
        jQuery(this).find('ul').stop(true,true).hide('fast');
        e.stopPropagation();
      })
    }
  })
  $('.languageChanger').hover(function(){
    $(this).find('ul').removeClass('hidden');
  }, function(){
    $(this).find('ul').addClass('hidden');
  });
}

//function passworAndUsername
function cleanUsernamePassword(){
	 jQuery('#login_dummy_password').val('');
	 jQuery('#login_password').val('');
	 jQuery('#login_username').val('');
}
function setupsmartSearchBehavior(){
  jQuery('#smart_content').focus(function(e){
	    this.select();
      jQuery(this).val('');
  });
  jQuery('#location_input').focus(function(e){
	    this.select();
      jQuery(this).val('');
  });
}
function passwordBehavior()
{
  jQuery('#login_dummy_password').focus(function(e){
	  this.select();
      jQuery(this).val('');
    jQuery('#login_dummy_password').addClass('hidden');
   jQuery('#login_password').removeClass('hidden').focus();
  });
  jQuery('#login_password').focus(function(e){
	  this.select();
      jQuery(this).val('');
  });
}
function bindMarkAsReadAndUnread()
{
  /*jQuery('.changeStatusRead').click(function (e)
    {
      var idelement = $(this).attr('id');
      var tourl = $(this).attr('url');
      //jQuery('.contentContainer').prepend(getLoading());
      jQuery.ajax(
       {
          type: 'POST',
          dataType: "html",
          url: tourl,
          data: ({messageId:idelement}),
          success: function(data) 
          {
            $('#message_div_'+idelement).html(data);
            $('.loading').hide();
          }
       }
      );
    }
  );
  jQuery('.changeStatusUnRead').click(function (e)
    {
      var idelement = $(this).attr('id');
      var tourl = $(this).attr('url');
      //jQuery('.contentContainer').prepend(getLoading());
      jQuery.ajax(
       {
          type: 'POST',
          dataType: "html",
          url: tourl,
          data: ({messageId:idelement}),
          success: function(data) 
          {
            $('#message_div_'+idelement).html(data);
            $('.loading').hide();
          }
       }
      );
    }
  );*/
}

function setSmartSideMenuBehavior(){
  jQuery('.smartSideMenu').find('a').each(function(){
    jQuery(this).click(function(e){
      var pageToCall = jQuery(this).attr('href');
      var callback = function(){
        bindFacebox();
        bindAccordionList();
        bindTabs();
      };
      if(jQuery(this).attr('callback'))
      {
        var callbackString = jQuery(this).attr('callback');
        callback = function(){
          setTimeout(callbackString, 1);
          bindFacebox();
          bindAccordionList();
          bindTabs();
        };
      }
      //make an AJAX call instead of following the link
      e.preventDefault();
      pageToCall += '/requestType/ajax';
      jQuery('.smartSideMenu').find('span').removeClass('smartSelected');
      jQuery(this).parent().addClass('smartSelected');
      jQuery('.smartContentContainer').prepend(getLoading());
      jQuery('.smartContentContainer').load(pageToCall+' .smartContentContainer', null, callback);
    });
  });
}

function setSideMenuBehavior()
{
  jQuery('.sideMenu').find('a').each(function(){
    jQuery(this).click(function(e){
      var pageToCall = jQuery(this).attr('href');
      if ($(this).hasClass('linkforceredirect'))
      {
        return true;
      }
      if($.browser.msie){
      window.location.href = pageToCall;
      }else{
      //if(browser != "Microsoft Internet Explorer")
      //{
      var callback = function(){
        bindFacebox();
        bindAccordionList();
        bindTabs();
        unbindForceredirect();
      };
      if(jQuery(this).attr('callback'))
      {
        var callbackString = jQuery(this).attr('callback');
        callback = function(){
          setTimeout(callbackString, 1);
          bindFacebox();
          bindAccordionList();
          bindTabs();
          unbindForceredirect();
        };
      }
      //make an AJAX call instead of following the link
      e.preventDefault();
      if(pageToCall.indexOf('?') == -1)
      {
        pageToCall += '?requestType=ajax';
      }
      else
      {
        pageToCall += '&requestType=ajax';
      }
      unbindForceredirect();
      jQuery('.sideMenu').find('span').removeClass('selected');
      jQuery(this).parent().addClass('selected');
      jQuery('.contentContainer').prepend(getLoading());
      jQuery.ajax({
               type: 'GET',
               dataType: "html",
               url: pageToCall,
               success: function(data) 
               {
                   var contentc = 
                     jQuery(data).find('.contentContainer');
                   
                   if (contentc.length > 0)
                   {
                     $('.contentContainer').html('');
                     $('.contentContainer').html(
                       contentc.html());
                   }
                   else
                   {
                     $('.contentContainer').html('');
                     $('.contentContainer').html(data);
                   }
                }
      });
      
      //jQuery('.contentContainer').load(pageToCall, null, callback);
    //}
    //else
    //{
    //  window.location.href = pageToCall;
    //}
      }
    });
  })
}

var map = null;
function loadMap() 
{
  var script = document.createElement("script");
  //script.src = "http://maps.google.com/jsapi?key=ABQIAAAAmQp0RBf9T9FRc281A-koiRQODyOIS5rzpoQ0tTplny0hHQOuqRRZsLUHRXe6xGRSII2AmnhJ25nbOA&amp;callback=loadMaps";
  //Add new key google map
    script.src = "http://maps.google.com/jsapi?key=ABQIAAAAzSH9WkvfHQ_h-t7xU3tJ5xQELYJliFhrqZ6ltngySSORPiFUURSNPYTw2lWjtNBYHp1HxR9gRClGXw&amp;callback=loadMaps";
  script.type = "text/javascript";
  //document.getElementsByTagName("head")[0].appendChild(script)

  try
  {
    if (GBrowserIsCompatible())
    {
      $(document).ready(function(){
        map = new GMap2(ID("map_canvas"));
        map.setUIToDefault();
        if(window.addOverlays)
        {
          addOverlays();
        }
        else
        {
          map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 2);
        }
      });
    }
  }
  catch(exception){}
}
function loadMap2() 
{
  var script = document.createElement("script");
  //script.src = "http://maps.google.com/jsapi?key=ABQIAAAAmQp0RBf9T9FRc281A-koiRQODyOIS5rzpoQ0tTplny0hHQOuqRRZsLUHRXe6xGRSII2AmnhJ25nbOA&amp;callback=loadMaps";
  script.src = "http://maps.google.com/jsapi?key=ABQIAAAAzSH9WkvfHQ_h-t7xU3tJ5xQELYJliFhrqZ6ltngySSORPiFUURSNPYTw2lWjtNBYHp1HxR9gRClGXw&amp;callback=loadMaps";
  script.type = "text/javascript";
  //document.getElementsByTagName("head")[0].appendChild(script)
  try
  {
      $(document).ready(function(){
        map = new GMap2(ID("map_canvas"));
        map.setUIToDefault();
        if(window.addOverlays)
        {
          addOverlays();
        }
        else
        {
          map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 2);
        }
      });
      
  }
  catch(exception){}
}
function loadMaps()
{
  var showMaps = function(){
    map = new google.maps.Map2(ID("map_canvas"));
    map.setUIToDefault();
    if(window.addOverlays)
    {
      addOverlays();
    }
  };
  google.load("maps", "2", {
    "callback" : showMaps
  });
}

function bindFacebox()
{
  jQuery('a[rel*=facebox]').facebox({
    ajax: 'remote.html'
  });
  jQuery('button[rel*=facebox]').facebox({
    ajax: 'remote.html'
  });
}

function showModal()
{
  $('#airValid').hide();
  jQuery('.modal').css('height',jQuery(document).height()).fadeIn('fast')
}

function closeModal()
{
  jQuery('.modal').css('height','0').fadeOut('fast', function (){
    $('#airValid').show();
  })
}

function paintDivs()
{
  jQuery(document).ready(function(){
    jQuery('.contentContainer > div').css('padding-left', '40px')
    jQuery('.contentContainer > div:odd').css('background','#EFF7FA')
    jQuery('.contentContainer > div:last-child').addClass('lastChild')
  })
}

function paintLeftPaddedDivs()
{
  jQuery(document).ready(function(){
    jQuery('.leftPadded > div:odd').css('background','#EFF7FA')
    jQuery('.leftPadded > div:last-child').addClass('lastChild')
  });
  jQuery(document).ready(function(){
    jQuery('.smartContentContainer > div').css('padding-left', '40px')
    jQuery('.smartContentContainer > div:odd').css('background','#EFF7FA')
    jQuery('.smartContentContainer > div:last-child').addClass('lastChild')
  })
}

function loadPeople(element, uri)
{
  jQuery(element).parent().parent().find('.people').load(uri);
}

function displayIE6Alert(uri)
{
  jQuery(document).ready(function(){
    jQuery('.ie6Alert').load(uri);
  });
}

function closeIE6()
{
  jQuery('.ie6Alert').html('');
}

function ID(id)
{
  return document.getElementById(id);
}

//used to edit the status message of the user profile
function editStatus()
{
  replaceWithTextbox('userPersonalMessage', 'status');
}

//function that binds the behavior of the generic accordion list
function bindAccordionList()
{
  jQuery('ul.accordionList li em').click(function(){
    jQuery(this).parent('li').children('ul').slideToggle('fast');
  });
  jQuery('ul.accordionList li em a').click(function(e){
    return false;
  });
}

//function that calls the photos to select a default picture when selecting a default media category for a saga
function sagaMediaCategoryChanged(value)
{
  if(value)
  {
    jQuery('#mediaCategoryPhotos').load(getScriptName()+'GotMedia/loadPhotos?categoryid='+value);
    jQuery('#saga_default_picture_id').val('');
  }
  else
  {
    jQuery('#mediaCategoryPhotos').html('');
    jQuery('#saga_default_picture_id').val('');
  }
}

//this function gets the scriptname to use symfony routing
function getScriptName()
{
  var uri = window.location.href;
  if(uri.indexOf('.php') != -1)
  {
    //we can view the .php extension
    return uri.substr(0,uri.indexOf('.php') + 5);
  }
  else
  {
    //the script is masked by mod-rewrite, return just the domain
    var segments = uri.split('/');
    return 'http://'+segments[2]+'/';
  }
}

//this function sets the hidden input with the selected image
function selectSagaImage(image, imageID)
{
  jQuery('#saga_default_picture_id').val(imageID);
  jQuery('#mediaCategoryPhotos').find('img').removeClass('gyCaptchaSelected').addClass('gyCaptchaUnselected');
  jQuery(image).removeClass('gyCaptchaUnselected').addClass('gyCaptchaSelected');
}

function showSagaMedia()
{
  jQuery('#sagaMedia').slideToggle('fast');
}

function switchRatingToEditMode(id, uri)
{
  var innerHtml = '';
  for (var i = 1; i < 11; i++)
  {
    innerHtml += '<a href="'+uri+'/rating/'+i+'">';
    if (i % 2 == 0)
    {
      innerHtml += '<img src="/images/right-bg-star.png" />';
    }
    else
    {
      innerHtml += '<img src="/images/left-bg-star.png" />';
    }
    innerHtml += '</a>';
  }
  jQuery('#'+id).html(innerHtml);
  jQuery('#'+id).find('img').hover(function(){
    jQuery(this).attr('src',jQuery(this).attr('src').replace(/bg\-/,''));
    jQuery(this).parent().prevAll().each(function(){
      jQuery(this).find('img').attr('src',jQuery(this).find('img').attr('src').replace(/bg\-/,''));
    })
  }, function(){
    jQuery(this).attr('src',jQuery(this).attr('src').replace(/\-star/,'-bg-star'));
    jQuery(this).parent().prevAll().each(function(){
      jQuery(this).find('img').attr('src',jQuery(this).find('img').attr('src').replace(/\-star/,'-bg-star'));
    })
  });
}
function businessRatingToserverBehavior(number, uri){
  jQuery.ajax({
               type: 'POST',
               dataType: "html",
               url: uri,
               data: ({num:number}),
               success: function(data) 
                 {
                     $('#ratingBusinessContainer').html('');
                     $('#ratingBusinessContainer').html(data);
                    }
                });
  return false;
}
function switchRatingToEditModeBusiness(id, uri)
{
  
  var innerHtml = '';
  for (var i = 1; i < 11; i++)
  {
    innerHtml += '<a href="'+uri+'/rating/'+i+'" onclick="businessRatingToserverBehavior('+i+',\''+uri+'\'); return false;">';
    if (i % 2 == 0)
    {
      innerHtml += '<img src="/images/right-bg-star.png" />';
    }
    else
    {
      innerHtml += '<img src="/images/left-bg-star.png" />';
    }
    innerHtml += '</a>';
  }
  jQuery('#'+id).html(innerHtml);
  jQuery('#'+id).find('img').hover(function(){
    jQuery(this).attr('src',jQuery(this).attr('src').replace(/bg\-/,''));
    jQuery(this).parent().prevAll().each(function(){
      jQuery(this).find('img').attr('src',jQuery(this).find('img').attr('src').replace(/bg\-/,''));
    })
  }, function(){
    jQuery(this).attr('src',jQuery(this).attr('src').replace(/\-star/,'-bg-star'));
    jQuery(this).parent().prevAll().each(function(){
      jQuery(this).find('img').attr('src',jQuery(this).find('img').attr('src').replace(/\-star/,'-bg-star'));
    })
  });
}
function ratingStarBehavior(element)
{
  $('#hidden_rating').val($(element).find('img').attr('value'));
  $(element).parent().find('a').attr('onmouseover', '').attr('onmouseout', '');
  $(element).parent().find('a').each(function(){
    $(this).find('img').attr('src',$(this).find('img').attr('src').replace(/bg\-/,''));
    $(this).find('img').attr('src',$(this).find('img').attr('src').replace(/\-star/,'-bg-star'));
  })
  $(element).find('img').attr('src',$(element).find('img').attr('src').replace(/bg\-/,''));
  $(element).prevAll().each(function(){
    $(this).find('img').attr('src',$(this).find('img').attr('src').replace(/bg\-/,''));
  });
}

function bindTabs()
{
  var tabs = $('.tabs');
  if(tabs.length)
  {
    tabs.tabs().show(1);
  }
  //this function also binds the autocomplete inputs for locations
  bindAutocomplete();
  bindAutocompleteSmartSearch();
  bindBusinessAutocomplete();
  bindContesPictureLocation();
  unbindForceredirect();
}
function bindContesPictureLocation(){
  jQuery('#country_name').autocomplete(getScriptName() + 'mostMagicalPlaces/populateCountries', {
	delay:10,
	minChars:1,
	timeout:1000,
	validSelection:false,
	cacheLength:15,
	maxItemsToShow:15
  });
  $("#country_name").result(function(event, data, formatted) {
    if(data){
      parsemostMagicalPlacesCountryData(data);
      /*var businesssData = data[1].split(',');
      jQuery('#smartcategory_id').val(businesssData[0])
      jQuery('#smartsubcategory').val(businesssData[1])
      jQuery('#smartbusiness_id').val(businesssData[2]);*/
    }
  });
}
function bindAutocompleteSmartSearch()
{
  jQuery('#smart_content').autocomplete(getScriptName() + 'SmartPages/populateSearcher', {
	delay:10,
	minChars:1,
	timeout:1000,
	validSelection:false,
	cacheLength:15,
	maxItemsToShow:15
  });
  $("#smart_content").result(function(event, data, formatted) {
    if(data){
      parseSmartContentSearchContentData(data);
      /*var businesssData = data[1].split(',');
      jQuery('#smartcategory_id').val(businesssData[0])
      jQuery('#smartsubcategory').val(businesssData[1])
      jQuery('#smartbusiness_id').val(businesssData[2]);*/
    }
  });
}

function bindAutocomplete()
{
  jQuery('#location_input').autocomplete(getScriptName() + 'GotPlaces/autocomplete', {
	delay:10,
	minChars:1,
	timeout:1000,
	validSelection:false,
	cacheLength:15,
	maxItemsToShow:15,
    extraParams: {
      presition: function(){
        return getPresition()
      }
    }
  });
  $("#location_input").result(function(event, data, formatted) {
    if (data)
    {
      parseLocationData(data);
    }
  });
  //when the presition changes we must clear the search results
  $('#search_location_presition').change(function(){
    $('#location_input').val('');
    parseLocationData(new Array('', ',,,'));
  })
}

function bindBusinessAutocomplete()
{
  $('#business_input').autocomplete(getScriptName() + 'SmartPages/autocomplete', {
    delay:10
  });
  $("#business_input").result(function(event, data, formatted) {
    if (data)
    {
      parseBusinessData(data);
    }
  });
}

function parseBusinessData(data)
{
  $('#business_autocomplete_id').val(data[1]);
}

function getPresition()
{
  var presition = $('#search_location_presition');
  if(presition.length == 0)
  {
    return '';
  }
  else
  {
    return presition.val();
  }
}

function parseLocationData(data)
{
  var locationData = data[1].split(',');
  jQuery('#location_input_region_id').val(locationData[0]);
  jQuery('#location_input_country_id').val(locationData[1]);
  jQuery('#location_input_state_id').val(locationData[2]);
  jQuery('#location_input_city_id').val(locationData[3])
  jQuery('#city_x').val(locationData[4])
  jQuery('#city_y').val(locationData[5])
}
function parseSmartContentSearchContentData(data){
  
  var businessData = data[1].split(',');
  jQuery('#smartcategory_id').val(businessData[0])
  jQuery('#smartsubcategory').val(businessData[1])
  jQuery('#smartbusiness_id').val(businessData[2]);
}

function parsemostMagicalPlacesCountryData(data)
{
  
  var businessData = data[1].split(',');
  jQuery('#uploader_country_id').val(businessData[0]);
}

function saveSubcategoryInSearchPart(id){
      var content = jQuery('#'+id).attr('cont');
      jQuery('#smartcategory_id').val('')
      jQuery('#smartsubcategory').val(id)
      jQuery('#smartbusiness_id').val('')
      jQuery('#smart_content').val(content)
      jQuery('#smartSearchForm').submit();
  }
function getPlaceSelectorValues()
{
  if($('#location_input_region_id').val() == '')
  {
    return false;
  }
  var string = '';
  string += 'region_id=' + $('#location_input_region_id').val();
  string += '&country_id=' + $('#location_input_country_id').val();
  string += '&state_id=' + $('#location_input_state_id').val();
  string += '&city_id=' + $('#location_input_city_id').val();
  return string;
}

function addForm(element, html)
{
  var innerUl = jQuery(element).parent().children('ul');
  if(innerUl.length == 0)
  {
    //if the parent does not have a inner list, add it
    jQuery(element).parent().append('<ul></ul>');
  }
  //we get the inner ul again so we'll grab the one we inserted too
  jQuery(element).parent().children('ul').append('<li>' + html + '</li>');
  jQuery(element).parent().children('ul').find('input[type=text]').focus();
}

function showPhotosFromCategory(uri)
{
  jQuery('#photos').prepend(getLoading()).load(uri, null, function(){
    bindPhotoSelector();
  });
}

function getSymfonyId(name)
{
  var id = name;
  if(name.substr(name.length - 1,1) == ']')
  {
    id = id.substr(0, name.length - 1 );
  }
  return id.replace('[','_').replace(']','_');
}

var photoSelectorName
function bindPhotoSelector(name)
{
  if (name != null)
  {
    photoSelectorName = getSymfonyId(name);
  }
  jQuery('#photos').ready(function(){
    jQuery('#photos img').click(function(){
      jQuery('#photos img').removeClass('selected');
      jQuery('#'+photoSelectorName).val(jQuery(this).attr('id'));
      jQuery(this).addClass('selected')
    });
  });
}

function setBox(name, value)
{
  jQuery('#'+getSymfonyId(name)).val(value);
  if (numberOfUploaders > 0)
  {
    numberOfUploaders = numberOfUploaders - 1;
    if(numberOfUploaders == 0)
    {
      closeModal();
      if(redirectWhenUploadsDone != '')
      {
        window.location.href = redirectWhenUploadsDone;
      }
    }
  }
}

function displayUploadedPhoto(id)
{
  var preview = jQuery('#previewPhoto');
  if (preview.length)
  {
    preview.attr('src',preview.attr('src').replace('++file++', id)).removeClass('hidden');
  }
  var link = jQuery('#reloadLink');
  if (link.length)
  {
    link.removeClass('hidden');
  }
  var categorySelect = $('.category_multimedia');
  categorySelect.each(function(){
    var categorySelector = $(this).parent().parent().find('select');
    if(categorySelector.length)
    {
      //we are in a quick upload inside a category selector partial for sharing media categories
      $(this).load(getScriptName()+'GotMedia/showOnlyPhotosFromCategory?id='+categorySelector.val());
    }
    var categoryId = $(this).parent().attr('category_id');
    if(categoryId)
    {
      $(this).load(getScriptName()+'GotMedia/showOnlyPhotosFromCategory?id='+categoryId);
    }
  });
}

function showUploadForm()
{
  jQuery('#previewImage').addClass('hidden');
  jQuery('#imageUploadForm').removeClass('hidden');
}

function addCategoryUploader(categoryID)
{
  addUploader($('#category_'+categoryID));
}

function addUploader(element, category, showSubmit)
{
  var extra = '';
  if(showSubmit)
  {
    extra = '/showSubmit/true';
  }
  if(category == null)
  {
    category = '+';
  }
  var uniqueName = new Date().getTime();
  element.append('<div id="upload"><iframe id="uploader_' + uniqueName + '" scrolling="no" src="'+getScriptName()+'GotMedia/iframe/name/category_uploader/uniqueName/'+uniqueName+'/categoryID/'+category+extra+'"></div>');
}

function removeUploader(uniqueName)
{
  $('#uploader_' + uniqueName).parent().remove();
}

function validateAllUploaders()
{
  var returnBool = true;
  var iframes = $(document).find('iframe');
  for(var i = 0; i < iframes.length; i++)
  {
    var iframe = iframes[i];
    returnBool = returnBool && iframe.contentWindow.validateForm();
  }
  return (returnBool);
}

var numberOfUploaders = 0;

function uploadWithAllUploaders(categoryID)
{
  if(validateAllUploaders())
  {
    numberOfUploaders = $(document).find('iframe').length;
    $(document).find('iframe').each(function(){
      $(this).contents().find('#local_photo_media_category_id').val(categoryID);
      this.contentWindow.upload();
    });
  }
}

function quickCreateGallery(title)
{
  $.post(
    getScriptName()+'GotSagas/quickCreateGallery/title/'+title,
    null,
    function(data){
      uploadWithAllUploaders(data.id);
    },
    'json'
    );
}

var redirectWhenUploadsDone = '';
function megaUploader(title, redirect)
{
  if(redirect != null)
  {
    redirectWhenUploadsDone = redirect;
  }
  if(validateAllUploaders())
  {
    showModal();
    quickCreateGallery(title);
  }
}
function goContactoUsOfAdvertise()
{
	//alert(getScriptName());
	window.location.href = getScriptName()+'/GotInfo/index?page=contact';
}


function setSagaCategory(sagaId, galleryId, redirectUri)
{
  $.post(
    getScriptName()+'GotSagas/quickLinkSagaToGallery/saga/'+sagaId+'/gallery/'+galleryId,
    null,
    function(data){
      $('.contentContainer').prepend(getLoading());
      $('.contentContainer').load(redirectUri);
    },
    'json'
    );
}

function addShareMediaBox()
{
  var numberOfBoxes = $('#sharingBoxes').children().length;
  var boxToAppend = numberOfBoxes + 1;
  $('#sharingBoxes').append('<div id="shareBox_'+boxToAppend+'"></div>');
  $('#shareBox_'+boxToAppend).load(getScriptName()+'GotMedia/sharingBox?box='+boxToAppend, null, function(){
    bindTabs();
    unbindForceredirect();
    $('#shareSubmit').removeClass('hidden');
  });
}

function ajaxTranslate(element, code)
{
  var text = element.html();
  //must trim all html elements so the text can be translated
  text = text.replace(/<.*?>/g, '');
  element.prepend(getLoading());
  google.language.detect(text, function(result){
    if (!result.error && result.language)
    {
      google.language.translate(text, result.language, code.toLowerCase(), function(result) {
        if (result.translation)
        {
          element.html(result.translation);
        }
        else
        {
          element.html(text);
        }
      });
    }
  });
}

function changePrivacyDropdowns(value)
{
  var index = null;
  if(value)
  {
    switch(value)
    {
      case 'public':
        index = 0;
        break;
      case 'friends':
        index = 1;
        break;
      case 'private':
        index = 2;
        break;
    }
    if (index != null)
    {
      ID('privacy_configuration_show_name').selectedIndex = index;
      ID('privacy_configuration_show_personal_information').selectedIndex = index;
      ID('privacy_configuration_show_business_information').selectedIndex = index;
      ID('privacy_configuration_show_wall').selectedIndex = index;
      ID('privacy_configuration_show_comments').selectedIndex = index;
    }
  }
}

function addFeedComment(feedId, saveUrl, _type)
{  
  var comment = $('#comment_'+feedId).val();

  if (comment)
  {
    $('#show_comments_'+feedId).load(saveUrl, {
      'comment': comment,
      'feedId': feedId,
      'type':  _type
    });
  }
}

function ajaxLoad(element, extraUrlParams, update)
{
  if(update == null)
  {
    update = '.contentContainer';
  }
  if(extraUrlParams == null)
  {
    extraUrlParams = '';
  }
  var pageToCall = $(element).attr('href');
  var callback = null;
  if($(element).attr('callback') == undefined)
  {
    callback = function(){
      bindFacebox();
      bindAccordionList();
      bindTabs();
      unbindForceredirect();
    };
  }
  else
  {
    var callbackString = $(element).attr('callback');
    callback = function(){
      bindFacebox();
      bindAccordionList();
      bindTabs();
      unbindForceredirect();
      setTimeout(callbackString, 1);
    };
  }
  if($(element).attr('callbefore') != undefined)
  {
    setTimeout($(element).attr('callbefore'), 1);
  }
  if(pageToCall.indexOf('?') == -1)
  {
    pageToCall += '/requestType/ajax';
  }
  else
  {
    pageToCall += '&requestType=ajax';
  }
  //make an AJAX call instead of following the link
  loadInElement(update, pageToCall+extraUrlParams, null, callback)
  return false;
}

function loadInElement(update, pagetocall, post, callback)
{
  if (update == null)
  {
    update = '.contentContainer';
  }
  $(update).prepend(getLoading());
  $(update).load(pagetocall, post, callback);
}

function showChatBanner(path)
{
  var htm = AC_FL_RunContent(
    'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0',
    'width', '533',
    'height', '345',
    'src', '/swf/gotchat?xml=' + path + '/swf/gotchat.xml',
    'quality', 'high',
    'pluginspage', 'http://www.adobe.com/go/getflashplayer',
    'align', 'middle',
    'play', 'true',
    'loop', 'true',
    'scale', 'showall',
    'wmode', 'transparent',
    'devicefont', 'true',
    'id', 'gotchat',
    'name', 'gotchat',
    'menu', 'true',
    'allowFullScreen', 'false',
    'allowScriptAccess','sameDomain',
    'movie', '/swf/gotchat?xml=' + path + '/swf/gotchat.xml',
    'salign', ''
    );
  $('#chatBanner').html(htm);
}

function showGallery()
{
  // We only want these styles applied when javascript is enabled
  $('div.navigation').css({
    'width' : '300px',
    'float' : 'left'
  });
  $('div.content').css('display', 'block');

  // Initially set opacity on thumbs and add
  // additional styling for hover effect on thumbs
  var onMouseOutOpacity = 0.67;
  $('#thumbs ul.thumbs li').css('opacity', onMouseOutOpacity)
  .hover(
    function () {
      $(this).not('.selected').fadeTo('fast', 1.0);
    },
    function () {
      $(this).not('.selected').fadeTo('fast', onMouseOutOpacity);
    }
    );

  // Initialize Advanced Galleriffic Gallery
  var galleryAdv = $('#gallery').galleriffic('#thumbs', {
    delay:                  2000,
    numThumbs:              12,
    preloadAhead:           10,
    enableTopPager:         true,
    enableBottomPager:      true,
    imageContainerSel:      '#slideshow',
    controlsContainerSel:   '#controls',
    captionContainerSel:    '#caption',
    loadingContainerSel:    '#loading',
    renderSSControls:       true,
    renderNavControls:      true,
    playLinkText:           'Play Slideshow',
    pauseLinkText:          'Pause Slideshow',
    prevLinkText:           '&lsaquo; Previous Photo',
    nextLinkText:           'Next Photo &rsaquo;',
    nextPageLinkText:       'Next &rsaquo;',
    prevPageLinkText:       '&lsaquo; Prev',
    enableHistory:          true,
    autoStart:              false,
    onChange:               function(prevIndex, nextIndex) {
      $('#thumbs ul.thumbs').children()
      .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
      .eq(nextIndex).fadeTo('fast', 1.0);
    },
    onTransitionOut:        function(callback) {
      $('#caption').fadeTo('fast', 0.0);
      $('#slideshow').fadeTo('fast', 0.0, callback);
    },
    onTransitionIn:         function() {
      $('#slideshow').fadeTo('fast', 1.0);
      $('#caption').fadeTo('fast', 1.0);
    },
    onPageTransitionOut:    function(callback) {
      $('#thumbs ul.thumbs').fadeTo('fast', 0.0, callback);
    },
    onPageTransitionIn:     function() {
      $('#thumbs ul.thumbs').fadeTo('fast', 1.0);
    }
  });
}

function gallery(element, textElement)
{
  this.element = element;
  this.text = textElement;

  this.select = function(element)
  {
    if(element.length)
    {
      $(element)
      .addClass('visible')
      .animate({
        width: $(element).attr('orig_width') + 'px'
      }, 200)
      .parent()
      .css('display', '')
      .animate({
        opacity: 1,
        width: 200 + 'px'
      }, 200);
      var prev = $(element).parent().prev().find('img');
      if(prev.length)
      {
        prev
        .removeClass('visible')
        .animate({
          width: (prev.attr('orig_width') / 3) + 'px'
        }, 200)
        .parent()
        .css('display', '')
        .animate({
          opacity: 0.7,
          width: (200 / 3) + 'px'
        }, 200);
      }
      prev = $(element).parent().prev().prev().find('img');
      if(prev.length)
      {
        prev
        .removeClass('visible')
        .animate({
          width: (prev.attr('orig_width') / 9) + 'px'
        }, 200)
        .parent()
        .css('display', '')
        .animate({
          opacity: 0.4,
          width: (200 / 9) + 'px'
        }, 200);
      }
      prev = prev.parent().prevAll().find('img');
      if(prev.length)
      {
        prev.each(function(){
          if($(this).parent().css('display') != 'none')
          {
            $(this)
            .removeClass('visible')
            .animate({
              width: 1 + 'px'
            }, 200)
            .parent()
            .css('display', '')
            .animate({
              opacity: 0,
              width: 1 + 'px'
            }, 200, null, function(){
              $(this).css('display', 'none');
            });
          }
        })
      }
      var next = $(element).parent().next().find('img');
      if(next.length)
      {
        next
        .removeClass('visible')
        .animate({
          width: (next.attr('orig_width') / 3) + 'px'
        }, 200)
        .parent()
        .css('display', '')
        .animate({
          opacity: 0.7,
          width: (200 / 3) + 'px'
        }, 200);
      }
      next = $(element).parent().next().next().find('img');
      if(next.length)
      {
        next
        .removeClass('visible')
        .animate({
          width: (next.attr('orig_width') / 9) + 'px'
        }, 200)
        .parent()
        .css('display', '')
        .animate({
          opacity: 0.4,
          width: (200 / 9) + 'px'
        }, 200);
      }
      next = next.parent().nextAll().find('img');
      if(next.length)
      {
        next.each(function(){
          if($(this).parent().css('display') != 'none')
          {
            $(this)
            .removeClass('visible')
            .animate({
              width: 1 + 'px'
            }, 200)
            .parent()
            .css('display', '')
            .animate({
              opacity: 0,
              width: 1 + 'px'
            }, 200, null, function(){
              $(this).css('display', 'none');
            });
          }
        });
      }
      this.displayText(element);
    }
  }

  this.displayText = function(element)
  {
    if (this.text != null)
    {
      var html = '<div>Title: '+$(element).attr('title')+'</div>';
      html += '<div>Description: '+$(element).attr('description')+'</div>';
      $(this.text).html(html);
    }
  }

  //first remove any existing bindings to prevent duplicate actions
  $(window).unbind('keyup');
  //bind the keys to the document to cycle the photos
  $(window).keyup(function(e){
    var key = e.keyCode ? e.keyCode : e.which;
    switch(key)
    {
      case 37:
        gall.select($(gall.element + ' img.visible').parent().prev().find('img'));
        break;
      case 39:
        gall.select($(gall.element + ' img.visible').parent().next().find('img'));
        break;
    }
  });

  //now bind the selection of photos
  $(this.element).find('img').click(function(e){
    if($(this).hasClass('visible'))
    {
      
    }
    else
    {
      e.preventDefault();
      gall.select($(this));
    }
  });

  //Now we set the default image style
  $(this.element).find('img').each(function(){
    $(this)
    .removeClass('visible')
    .css('height', ($(this).height()) + 'px')
    .css('width', '')
    .attr('orig_width', $(this).width())
    .css('width', '1px')
    .parent()
    .css('opacity', '0')
    .css('display', 'none');
  });


  //select by default the first image
  this.select(this.element + ' a:first-child img');

  return this;
}

function goToLocation()
{
  var presition = $('#search_location_presition').val();
  var country = $('#location_input_country_id').val();
  var city = $('#location_input_city_id').val();
  if(presition == 'country')
  {
    if(country)
    {
      window.location.href = getScriptName()+'GotPlaces/countryRedir/countryID/'+country;
    }
  }
  else
  {
    if(city)
    {
      window.location.href = getScriptName()+'city/'+city;
    }
  }
}

function showUiDialog(message, title, buttons)
{
  if(!title)
  {
    title = '';
  }
  if(!buttons)
  {
    buttons = {
      X: function()
      {
        $(this).dialog('close');
      }
    };
  }
  $('.dialog').html('<div class="hidden" id="dialog"></div>');
  $('#dialog').attr('title',title);
  $('#dialog').html(message);
  $("#dialog").dialog({
    bgiframe: true,
    modal: true,
    buttons: buttons
  });
}
function trimBusinessName(s){
//s = s.replace(/\s+/gi, ' '); //sacar espacios repetidos dejando solo uno
//s = s.replace(/^\s+|\s+$/gi, ''); //sacar espacios blanco principio y final
s = s.replace(/^\s*/, "");
s = s.replace(/\s*$/, "");
s = s.replace(/\s+/gi, " ");
return s;
}
function isUrlHttp(s) {
	//var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	var regexp =  /^(http|https):\/\/(\S+).(com|net|org|info|biz|ws|us|tv|cc)$/i;
  return regexp.test(s);
}
function isUrl(s) {
	//var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	var regexp =  /^(http|https):\/\/(\S+).(com|net|org|info|biz|ws|us|tv|cc)$/i;
  return regexp.test(s);
}
function urlhasProtocol(s)
{
  var regexp = /(http|https)/i;
  return regexp.test(s);
}

function validateSmartUrl(s)
{
  var regexp = /^(http)s?:\/\/\w+([\.\-\w]+)?\.([a-z]{2,3}|info|mobi|aero|asia|name)(:\d{2,5})?(\/)?((\/).+)?$/i;
  return regexp.test(s);
}

function isUrlwww(s) {
	//var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	var regexp =  /^\w+.(\S+).(com|bo|uk|es|net|org|info|biz|ws|us|tv|cc)$/i;
  return regexp.test(s);
}
function urlencode(str) {
    return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
    }
/**business part**/

function rotateImage(id, element)
{
  var identifierphoto = id; 
  $.ajax({
    type: 'POST',
    dataType: "html",
    url: '/index.php/GotMedia/rotatePicture',
    data: ({idpicture:identifierphoto}),
    success: function(data) 
    {
      $('#'+element+id+'').html(data);
    }
  });
}
function validateEmailAddress(emailAddress)
{
  var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
  return pattern.test(emailAddress);
}


function insertImageinEditor(elementsrc)
{
  //alert(elementsrc);
  tinyMCE.execCommand('mceInsertContent', false, '<img src="'+elementsrc+'" mce_src="'+elementsrc+'"/>', 1);
}

function renderErrorFormFile(idelement,iderrorelement,message)
{
  $('#'+idelement).css('border','1px solid red');
  $('#'+idelement).css('background-color','IndianRed');
  if($('#'+iderrorelement).length == 0)
  {
    $('#'+idelement).before('<span id="'+iderrorelement+'" style="font-size:11px; color: red;">'+message+'<br /></span>');
  }
  else
  {
    $('#'+iderrorelement).html(message+'<br />');
  }
}

function renderErrorForm(idelement,iderrorelement,message)
{
  $('#'+idelement).css('border','1px solid red');
  $('#'+idelement).css('background-color','IndianRed');
  if($('#'+iderrorelement).length == 0)
  {
    $('#'+idelement).before('<span id="'+iderrorelement+'" style="font-size:11px; color: red;">'+message+'<br /></span>');
  }
  else
  {
    $('#'+iderrorelement).html(message+'<br />');
  }
}

function cleanErrorForm(idelement,iderrorelement)
{
  $('#'+idelement).css('border','1px solid #22659A');
  $('#'+idelement).css('background-color','white');
  $('#'+iderrorelement).html('');
}

function reloadGallery(idgallery, tourl)
{
  showImagesUploading();
  $.ajax({
    type: 'POST',
    url: tourl,
    data: {idgal: idgallery},
    success: function(msg) {
        $('#carouselImages').html(msg);
        hideImagesUploading();
      }
  });
}

function renderElementToSaga(el)
{
  var src = el.parent().parent().find('img').attr('altsrc');
  showImageUploadingToSaga();
  insertImageinEditor(src);
  hideImageUploadingToSaga();
  jQuery(document).trigger('close.facebox');
  closeModal();
  return false;
}
function showImageUploadingToSaga()
{
  jQuery('#loadingimageToSaga').css('display', 'inline');
}
function hideImageUploadingToSaga()
{
  jQuery('#loadingimageToSaga').css('display', 'none');
}
function showImagesUploading()
{
  jQuery('#loadingimages').css('display', 'inline');
}
function hideImagesUploading()
{
  jQuery('#loadingimages').css('display', 'none');
}

function voteElement(idelement, tablename, urltoVote)
{
  //showLoadindInElement('#counterId'+tablename+idelement);
  $.ajax({
    type: 'POST',
    dataType: "html",
    url: urltoVote,
    data: {elementId: idelement, nameTable: tablename},
    success: function(msg) {
        $('#counterId'+tablename+idelement).html(msg);
      }
  });
}

function selectBaseImageToAnotherService($travelTipId, $idpicture, urltochangedefaultPic)
{
  $.ajax({
    type: 'POST',
    dataType: "json",
    url: urltochangedefaultPic,
    data: {traveltipId: $travelTipId, idpicture: $idpicture},
    success: function(msg) {
        if (msg.detail == '1')
        {
          //console.log('ok');
        }
        else
        {
          //error
          //console.log('not ok');
        }
        return true;
      }
  });
//  console.log($travelTipId+'  '+$idpicture+'  '+urltochangedefaultPic);
  return false;
  
}

function helpGoToPage1()
{
  $('.slideHelp').slideUp();
  $('#slidehelp1').slideDown('slow');
}

function helpGoToPage2()
{
  $('.slideHelp').slideUp();
  $('#slidehelp2').slideDown('slow');
}

function forceredirect(url)
{
  window.location.href = url;
}


function baseReadCookie(name)
{
   var a = document.cookie.substring(document.cookie.indexOf(name + '=') + name.length + 1, document.cookie.length);
   if(a.indexOf(';') != -1){
	   a = a.substring(0,a.indexOf(';'));
   }
   return a; 
}

function checkFBloginpart(){
  FB.getLoginStatus(function(response){
    if(response.authResponse){
      window.location.reload(true);
    };
  });
}
