var FirstOption = ''; //holds FaleConnosco Form option;
 
$(function() {
  // Fix z-index
  var zIndexNumber = 20000;
  $('div').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
  });
  
  CorrectMenus();  //Adjust SubMenu and load DropdownMenu
  
  // Breadcrumb fix
  $("span.SeperatorText:first").remove();
  $("span.LegendText:last, span.LegendText:last a").css("color", "#3598a5");				// General pages
  $("div.TopPages span.LegendText:last, div.TopPages span.LegendText:last a").css("color", "#2952a1");	// Top Menu pages
  
  // iFrame tabs
  CorrectTabsWidth();
  $("#iframe_flowTabs").tabs("#iframe_flowPanes > div", {
    //history: true,
    effect: 'fade',
    onBeforeClick:function(event,tabIndex){
      this.getCurrentPane().addClass("current");
    }
  });
  
  // Paragraph Setup - Client Support
  $("#SectionEmailTabs li, #SectionPhoneTabs li").wrapInner('<a href="javascript:void(0)"></a>');
  $("#SectionEmailTabs li:last a, #SectionPhoneTabs li:last a").css({'border-right-width': '0px', 'padding-right':'0', 'margin-right':'0'});
  $("#SectionEmailTabs").tabs("#SectionEmailPanes > div", {
    effect: 'slide',
    onBeforeClick:function(event,tabIndex){
      this.getCurrentPane().addClass("current");
    }
  });
  $("#SectionPhoneTabs").tabs("#SectionPhonePanes > div", {
    effect: 'slide',
    onBeforeClick:function(event,tabIndex){
      this.getCurrentPane().addClass("current");
    }
  });
  
  // Column Paragraphs correction - Escapadinhas
  $("div.ParagraphColumn:odd").css({
    'margin-right': '0',
    'border-right': '0',
    'padding-right': '0'
  });
  $("div.ParagraphColumn:last").after('<div class="clear"></div>');
  
  // Stores fix
  $("div.StoreMap").siblings("br").remove();
  $(".MapLocationHeader").each(function() {
    $(this).prev().css({
      'margin-bottom': '2px',
      'padding-bottom': '0px',
      'border-bottom': 'none'
    });
  });
  $("div.ParagraphText").find("div.StoreMap:last").each(function(index) {
    $(this).css({
      'padding-bottom': '0px',
      'border-bottom': 'none'
    });
    if (index != $("div.ParagraphText").length-1) {
      $(this).css('margin-bottom', '2px');
    } else {
      $(this).css('margin-bottom', '0px');
    }
  });
  
  // Tooltip
  $('li.StoreGraphics_Photo img').tooltip({ 
    delay: 0, 
    showURL: false, 
    top: -200,
    left: -235,
    bodyHandler: function() {
      if ($(this).parent().attr("href") != "javascript:void(0);") {
        return $("<img/>").attr("src", $(this).parent().attr("href"));
      }
      else {
        return "no zoom image";
      }
    } 
  });
  $('li.StoreGraphics_Photo a').each(function(link) {
    $(this).click(function(event){
      if (this.href != "javascript:void(0);") {
        event.preventDefault();
        window.open(this.href,'PopUpMap','width=200,height=170');
        return false;
      }
    });
  });
  
  //input files
  $("input[type=file]").filestyle({ 
    image: "Files/System/ViagensAbreu/layout/choose-file_v2.gif",
    imageheight : 19,
    imagewidth : 27,
    width : 207
  });
  
  //autoOpen tabs aqui
  
  var tabToOpen = 0;  
  if ($.getUrlVar("motor") == "voos") { tabToOpen = 1; }
  else if($.getUrlVar("motor") == "hotel") { tabToOpen = 2; }
  if (tabToOpen >= 0 && tabToOpen <=2 && $("#iframe_flowTabs").data("tabs"))
    window.setTimeout(function() { $("#iframe_flowTabs").data("tabs").click(tabToOpen);}, 100);
  document.domain = "abreu.pt";


});
 
 
 
function Process_iFrameSrc(type) {
  var urlVars = $.getUrlVars(),
      toRemoveList = ["goToPage", "AreaId", "PID", "NewsId", "M", "Action", "CategoryId"],
      newLocationSearch = '?',
      inArray = false;
      // ID was removed from the toRemoveList because of ViaTecla needs
  
  if (type == "append") newLocationSearch = '&';
  for (i=0; i<urlVars.length; i++) {
    inArray = false;
    for (l=0; l<toRemoveList.length; l++) {
      if (urlVars[i].toLowerCase() == toRemoveList[l].toLowerCase() || (urlVars[i].toLowerCase() == "motor" && type == "append")) {
        inArray = true;
        break;
      }
    }
    if (!inArray) newLocationSearch += urlVars[i].toLowerCase() + "=" + $.getUrlVar(urlVars[i]) + "&";
  }
  newLocationSearch = newLocationSearch.substring(0,newLocationSearch.length-1);
  return newLocationSearch;
}
 
 
 
function CorrectTabsWidth() {
  var TotalLiWidth = 0,
      TotalLi = $("#iframe_flowTabs li").length,
      TotalWidth = $("#LeftColumn").width()-(3*(TotalLi-1))-(2*TotalLi),  //Counting off 3px of margin for all but 1 <li> and 2px of border in all <li>
      Rounding = 0,
      NewWidth = 0;
  
  $("#iframe_flowTabs li").each(function() { TotalLiWidth+=$(this).outerWidth(); });
  NewWidth = Math.floor(TotalWidth/TotalLi);
  Rounding = TotalWidth % TotalLi;
  $("#iframe_flowTabs li").each(function(i) {
    if (i==1) {
      $(this).css("width", (NewWidth+Rounding) + "px");
      $(this).find("a").css("width", (NewWidth+Rounding) + "px");
    }
    else {
      $(this).css("width", NewWidth + "px");
      $(this).find("a").css("width", NewWidth + "px");
    }
  });
}
 
 
 
/* clears the general search box text */
function clearField( input, defaultValue ) {
    if( ( $('input[name="'+input+'"]').val() == "" ) || ( $('input[name="'+input+'"]').val().toLowerCase() == defaultValue.toLowerCase() ) )
        $('input[name="'+input+'"]').val("");
}
 
/* resets the general search box text to its default value */
function checkIfEmpty( input, defaultValue ) {
    if( ( $('input[name="'+input+'"]').val() == "" ) || $('input[name="'+input+'"]').val().toLowerCase() == defaultValue.toLowerCase() )
        $('input[name="'+input+'"]').val( defaultValue );
}
 
 
 
/* Social Links */
function CorrectSocialLinks() {
  $(".addToFacebook").each(function() {
    $(this).attr("href", "http://www.facebook.com/sharer.php?u=" + location.protocol + "//" + location.hostname + $(this).parent().parent().find("div.News_ReadMore a").attr("href") + "&amp;t=" + $(this).parent().parent().find("h2").text());
  });
  $(".addToTwitter").each(function() {
    $(this).attr("href", "http://twitter.com/home/?status=" + $(this).parent().parent().find("h2").text());
  });
  $(".addToBlogger").each(function() {
    $(this).attr("href", "http://www.addthis.com/bookmark.php?pub=AddThis&amp;v=250&amp;source=tbx-250&amp;tt=0&amp;s=google&amp;url=" + location.protocol + "//" + location.hostname + $(this).parent().parent().find("div.News_ReadMore a").attr("href") + "&amp;title=" + $(this).parent().parent().find("h2").text() + "&amp;content=&amp;lng=pt");
  });
}
 
 
 
/* Form "Fale Connosco" */
function ActivateExtraFields1(indexToActivate, RadioManager, SelectToToggle1, SelectToToggle2) {
  $("#" + RadioManager).change(function() {
    if($("input[name='" + RadioManager + "']:checked").index("input[name='" + RadioManager + "']") == indexToActivate) {
      $("#" + SelectToToggle1).parent().slideDown("slow");
      $("#" + SelectToToggle2).parent().slideDown("slow");
      $("#Form_FaleConnosco_Loja").parent().slideUp("slow", function() {
        $("#Form_FaleConnosco_Loja").prepend(FirstOption);
        $("#Form_FaleConnosco_Loja").get(0).selectedIndex = 0;
        $("#Form_FaleConnosco_Loja option:not(:first)").attr("disabled", "disabled");
        $("#Form_FaleConnosco_Loja").trigger("change");
      });
    }
    else {
      FirstOption = $("#Form_FaleConnosco_Loja option:first");
      $("#Form_FaleConnosco_Loja option:first").remove();
      //$("#" + SelectToToggle1).get(0).selectedIndex = 0;
      $("#Form_FaleConnosco_Loja").get(0).selectedIndex = 0;
      $("#Form_FaleConnosco_Loja").trigger("change");
      $("#Form_FaleConnosco_Loja option").attr("disabled", false);
      $("#" + SelectToToggle1).parent().slideUp("slow");
      $("#Form_FaleConnosco_Loja").parent().slideDown("slow");
      $("#" + SelectToToggle2).parent().slideUp("slow");
    }
  });
}
 
function ActivateExtraFields2(indexToActivate, RadioManager, RadioToToggle, SelectToToggle) {
  $("#" + RadioManager).change(function() {
    if($("input[name='" + RadioManager + "']:checked").index("input[name='" + RadioManager + "']") == indexToActivate) {
      $("#" + RadioToToggle).slideDown("slow");
      $("#" + SelectToToggle).parent().slideDown("slow");
    }
    else {
      $("#" + RadioToToggle).slideUp("slow", function() {
        $("#" + RadioToToggle).find("input").attr('checked', false);
      });
      $("#" + SelectToToggle).parent().slideUp("slow");
    }
  });
}
 
function limitChars(textid, limit) {
  var text = $("#"+textid).val();
  var textlength = text.length;
  if (textlength>limit) {
    $("#"+textid).val(text.substr(0,limit));
    return false;
  }
  else {
    return true;
  }
}
 
 
 
function CorrectMenus() {
  $("#MainMenu ul.M2").each(function() {
    resizeUls($(this));
  });
  $("#MainMenu ul.M3").each(function() {
    resizeUls($(this));
    $(this).css({
      "display": "none",
      "left": $(this).parent().outerWidth(true)+"px"
    });
  });
  
  $("#MainMenu ul.M2").each(function() {
    $(this).css({
      "display": "none",
      "top": parseInt($("#MainMenu ul.M1 li:first").height()) + "px"
    });
    if($.browser.msie) {
      var ieBorderWidth = 6;
      $(this).css({
        "border-top-width": ieBorderWidth + "px",
        "top": (parseInt($("#MainMenu ul.M1 li:first").height())- ieBorderWidth) + "px"
      });
    }
  });
  
  if ($("#MainMenu .M1").length) { $("#MainMenu .M1").css("width", ($("#MainMenu .M1").width()-$("#MainMenu li.inpath:first").position().left)+"px"); }  // SubMenu fix
  $("#MainMenu ul.M2 li.fly").siblings().css("padding-right","10px");                                                                // Correct padding when no 4th level exists
  $("#MainMenu ul.M1 ul").css("width", "auto");                                                                                      // Correct dropdown menu's width
  
  $("#MainMenu ul.M2").parent().hover(
    function () { $(this).find("ul.M2").stop(true, true).fadeIn("slow"); },
    function () { $(this).find("ul.M2").stop(true, true).fadeOut("slow"); }
  );
  $("#MainMenu ul.M3").parent().hover(
    function () { $(this).find("ul.M3").stop(true, true).fadeIn("slow"); }, 
    function () { $(this).find("ul.M3").stop(true, true).fadeOut("slow"); }
  );
}
 
function resizeUls(ulObject) {
  var BiggestItem = 0,
      ulHeight = 0;
  
  ulObject.children().each( function() {
    if (parseInt($(this).children().outerWidth(true)) > parseInt(BiggestItem)) {
      BiggestItem = $(this).children().outerWidth(true);
    }
  });
   
  ulObject.children().css("width", BiggestItem + "px");
  ulObject.children("li a").css({
    "width": $(this).parent().outerWidth(true) + "px"
  });
  
  // Correct Ul height
  ulObject.children().each(function() { ulHeight += parseInt($(this).outerHeight()); });
  ulObject.css("height", ulHeight + "px");
}
 
 
 
// Url Params jQuery extention
$.extend({
  getUrlVars: function(){
    SiteURL = window.location.href;
    while (SiteURL.indexOf("?") > -1)
     SiteURL = SiteURL.replace("?","&");
    SiteURL = SiteURL.replace("&", "?");
    
    var vars = [], hash,
        StartPosition = SiteURL.indexOf('?') + 1;
    var hashes = SiteURL.slice(StartPosition).split('&');
    if (StartPosition && StartPosition < SiteURL.length) {
      for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
      }
    }
    else {
      vars = "";
    }
    return vars;
  },
  getUrlVar: function(name) {
    return $.getUrlVars()[name];
  }
});
