var _lb;
var _ticker;

$(document).ready(function() {
  initNewsScroller();

  $("#searchbox-dropdown input[type=button]").click(function() {
    location.href = '/gac/Search.aspx?id=56915&start=0&SearchQueryStr=' + $("#searchbox-dropdown input[type=text]").val();
  });

  if ($("#main_nav").length > 0) {
    $("#main_nav li:not(#main_nav li li)").each(function() {
      if ($(this).find("ul").length > 0) {
        $(this).mouseenter(function() {
          $(this).find("ul").css({
            "position": "absolute",
            "left": $(this).find("a:eq(0)").offset().left + "px"
          });
          if ($("#main_nav li:not(#main_nav li li)").index($(this)) == $("#main_nav li:not(#main_nav li li)").length - 1) {
            $(this).addClass("last");
            $(this).find("ul").css({
              "left": ($(this).find("a:eq(0)").offset().left + $(this).outerWidth() - $(this).find("ul").outerWidth() + 4) + "px"
            });
          }
          $(this).addClass("hover");
          $(this).find("ul").show();
          $(this).find("ul li:first").addClass("first");
          $(this).find("ul li:last").addClass("last");
          if ($("#mapcontainer1, #mapcontainer2").length > 0) {
            $("#mapcontainer1, #mapcontainer2").css({
              "visibility": "hidden"
            });
          }
        });
        $(this).mouseleave(function() {
          $(this).removeClass("hover");
          $(this).find("ul").hide();
          if ($("#mapcontainer1, #mapcontainer2").length > 0) {
            $("#mapcontainer1, #mapcontainer2").css({
              "visibility": "visible"
            });
          }
        });
      }
    });
  }

  if ($("#main-services").length > 0) {
    $("#main-services .tabs a").click(function() {
      clickIndex = $("#main-services .tabs a").index($(this));
      $(this).siblings("a").removeClass("active");
      $(this).addClass("active");
      targetPanel = $("#main-services .panels div:eq(" + clickIndex + ")");
      targetPanel.siblings("div").removeClass("active");
      targetPanel.addClass("active");
      return false;
    });
  }

  $("input[type=button], input[type=submit]").each(function() {
    var aLink;
    if ($(this).attr("value") == "Next") {
      aLink = $('<a href="#" class="bt_next"><span>Next</span></a>');
    }
    else {
      if ($(this).closest("div").attr("id") == "searchbox-dropdown") {
        aLink = $('<a href="#" class="bt_searchgo"><span>Submit</span></a>');
      }
      else {
        if ($(this).attr("id") == "pageBody_SearchButton") {
          aLink = $('<a href="#" class="bt_searchgocolour"><span>Search</span></a>');
        }
        else {
          aLink = $('<a href="#" class="bt_submit"><span>Submit</span></a>');
        }
      }
    }

    aLink.click(function() {
      $(this).siblings("input[type=button], input[type=submit]").click();
      return false;
    });
    $(this).after(aLink).hide();
  });

  $("#quick-links-handle, #searchbox-handle").each(function() {
    $(this).after("<li>|</li>");
  });
  $("#quick-links-handle, #searchbox-handle, #worldmap-handle").each(function() {
    var linkText = $(this).find("a:eq(0)").text();
    $(this).find("a:eq(0)").html('<span>' + linkText + '</span>');

    switch ($(this).attr("id")) {
      case "quick-links-handle":
        $(this).find("div.dropdown").css({
          "position": "absolute",
          "right": 0,
          "margin-left": 0
        });
        break;
      case "searchbox-handle":
        $(this).find("div.dropdown").css({
          "position": "absolute",
          "right": 0,
          "margin-left": 0
        });
        break;
      case "worldmap-handle":
        $(this).find("div.dropdown").css({
          "position": "absolute",
          "right": 0,
          "margin-left": 0
        });
        break;
    }
    $(this)
		  .addClass("utility-link")
			.mouseenter(function() {
			  $(this).find("div.dropdown").first().show();
			  $(this).addClass("hover");
			  if ($("#mapcontainer1, #mapcontainer2").length > 0) {
			    $("#mapcontainer1, #mapcontainer2").css({
			      "visibility": "hidden"
			    });
			  }
			})
			.mouseleave(function() {
			  $(this).find("div.dropdown").first().hide();
			  $(this).removeClass("hover");
			  if ($("#mapcontainer1, #mapcontainer2").length > 0) {
			    $("#mapcontainer1, #mapcontainer2").css({
			      "visibility": "visible"
			    });
			  }
			})
    $(this).find("a:eq(0)").click(function() {
      return false;
    });
  });
  $("#worldmap-handle").find("a span").html('<span id="gac-worldwide-minimap">&nbsp;</span><span>' + $("#worldmap-handle").find("a span").text() + '</span>');

  $("#worldmap-handle div.dropdown table:eq(0)").find("td:not(td td):eq(0)").addClass("col-1");
  $("#worldmap-handle div.dropdown table:eq(0)").find("td:not(td td):eq(1)").addClass("col-2");
  $("#worldmap-handle div.dropdown table:eq(0)").find("td:not(td td):eq(2)").addClass("col-3");


  if ($('#lightbox').length > 0) {
    $("#lightbox-add-handle").click(function() {
      alert("My Services Box is being loaded, please wait and try again.");
      return false;
    });

    _lb = new Lightbox();
    _lb.init();
    $("#footer").css({
      "padding-bottom": parseInt($("#footer").css("padding-bottom")) + 40 + 'px'
    });
    $("#lightbox a.btn-expand").click(onClickLightboxExpandButton);
    $("#lightbox a.btn-close").click(onClickLightboxCloseButton);

    if ($("#lightbox-add-handle").length > 0) {
      $("#lightbox-add-handle").parent().parent().append("<p id='added_service_text' style='display: none;'>This service has been added.</p>");
    }

    if ($("#lightbox_contactme_submit")) {
      $("#lightbox_contactme_submit").click(function() {
        var servicesStr = "";
        for (var i = 0; i < _lb.services.length; i++) {
          if (_lb.services[i] != "") {
            servicesStr += '"' + $.URLEncode(_lb.services[i]) + '";';
          }
        }
        var serializeData = "";
        $.each($("#lightbox-form-contact :input"), function() {
          if ($(this).attr("name").length > 0) {
            serializeData += $(this).serialize() + "&";
            $(this).parent().parent().removeClass("error");
          }
        });

        $.ajax({
          url: "/gac/misc/services_contactme.aspx",
          type: "POST",
          data: serializeData + "services=" + servicesStr,
          dataType: "json",
          success: function(data) {
            if (data.isvalid == false) {
              $.each(data.err_fields, function(key, value) {
                $("#lightbox-form-contact input[name='" + value + "']").parent().parent().addClass("error");
                $("#lightbox-form-contact select[name='" + value + "']").parent().parent().addClass("error");
                $("#lightbox-form-contact textarea[name='" + value + "']").parent().parent().addClass("error");
              });
            } else if (data.isvalid == true) {
              $("#lightbox-form-contact .success").show();
              $("#lightbox-form-contact table").hide();
            }
          }
        });

        return false;
      });
    }

    if ($("#lightbox_email_submit")) {
      $("#lightbox_email_submit").click(function() {
        var servicesStr = "";
        for (var i = 0; i < _lb.services.length; i++) {
          if (_lb.services[i] != "") {
            servicesStr += '"' + $.URLEncode(_lb.services[i]) + '";';
          }
        }
        var serializeData = "";
        $.each($("#lightbox-form-email :input"), function() {
          if ($(this).attr("name").length > 0) {
            serializeData += $(this).serialize() + "&";
            $(this).parent().parent().removeClass("error");
          }
        });

        $.ajax({
          url: "/gac/misc/services_emailme.aspx",
          type: "POST",
          data: serializeData + "services=" + servicesStr,
          dataType: "json",
          success: function(data) {
            if (data.isvalid == false) {
              $.each(data.err_fields, function(key, value) {
                alert(value);
                $("#lightbox-form-email input[name='" + value + "']").parent().parent().addClass("error");
                $("#lightbox-form-email select[name='" + value + "']").parent().parent().addClass("error");
                $("#lightbox-form-email textarea[name='" + value + "']").parent().parent().addClass("error");
              });
            } else if (data.isvalid == true) {
              $("#lightbox-form-email .success").show();
              $("#lightbox-form-email table").hide();
            }
          }
        });

        return false;
      });
    }
    if ($("#lightbox-link-print")) {
      $("#lightbox-link-print").click(function() {

        var iframe_content = $("<iframe>");
        iframe_content.attr({
          "id": "lightbox_print_iframe",
          "src": "/gac/misc/lightbox_print.aspx"
        });

        if ($("#lightbox_print_iframe").length > 0) {
          $("#lightbox_print_iframe").remove();
        }
        $(this).hide();
        $("#lightbox-print-loader").show();
        $("#lightbox-form-print").append(iframe_content);

        return false;
      });
    }

    if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6) {
      $("#lightbox .summary .item-count").html('<span>' + $("#lightbox .summary .item-count").text() + '</span>');
      setInterval(updateFixedPosition, 100);
    }
  }

  $("#news_scroller > ul > li > a").click(onClickNewsSliderButton);

  if ($("#news_scroller")) {
    _ticker = setInterval(scrollNews, 5000);
  }

  if ($("#emailthispage")) {
    try {
      $("#emailthispage").dialog({
        autoOpen: false,
        height: 370,
        width: 360,
        modal: true,
        resizable: false,
        draggable: false
      });
    }
    catch (ex) { }
    $("#emailthispage-link").click(function() {
      $("#emailthispage").find("input.text, textarea").each(function() {
        this.value = "";
      });
      $("#emailthispage-formview").show();
      $("#emailthispage-successview").hide();
      $("#emailthispage").dialog("open");

      return false;
    });
    $("#emailthispage-submit").click(function() {
      $("#emailthispage-url").val(window.location);
      var serializeData = "";
      $.each($("#emailthispage-formview :input"), function() {
        if ($(this).attr("name").length > 0) {
          serializeData += $(this).serialize() + "&";
          $(this).parent().parent().removeClass("error");
        }
      });
      $.ajax({
        url: "/gac/misc/emailthispage.aspx",
        type: "POST",
        data: serializeData,
        dataType: "json",
        success: function(data) {
          if (data.isvalid == false) {
            $.each(data.err_fields, function(key, value) {
              $("#emailthispage-formview input[name='" + value + "']").parent().parent().addClass("error");
              $("#emailthispage-formview select[name='" + value + "']").parent().parent().addClass("error");
              $("#emailthispage-formview textarea[name='" + value + "']").parent().parent().addClass("error");
            });
          } else if (data.isvalid == true) {
            $("#emailthispage-formview").hide();
            $("#emailthispage-successview").show();
          }
        },
        error: function(r, t, s) {
        }
      });
      return false;
    });
    $("#emailthispage-cancel").click(function() {
      $("#emailthispage").dialog("close");
      return false;
    });
  }
});

function scrollNews(el) {
  var dir = "down";
  var ticker = $("#news_scroller li.active ul");
  if (isNaN(el) && $(el).is("a.news_scroll_up_arrow")) {
    dir = "up";
  }
  if (dir == "down") {
    var clonedMe = ticker.find("li:first").clone();
    ticker.append(clonedMe);
    ticker.find("li:first").slideUp('slow', function() {
      $(this).remove();
    });
  }
  else {
    var cloned = ticker.find("li:last").first().clone();
    cloned.hide();
    ticker.find("li:last").remove();
    ticker.prepend(cloned);
    cloned.slideDown('slow', function() {
    });
  }
}

function onClickLightboxExpandButton() {
    $("#lightbox .content").show();
    $("#lightbox .summary").fadeOut(100, function() {
        $("#lightbox").animate({
            height: 250
        }, 500);
    });

    return false;
}

function onClickLightboxCloseButton() {
    $("#lightbox").animate({
        height: 20
    }, 200, "", function() {
        $("#lightbox .summary").fadeIn(100);
        $("#lightbox .content").hide();
    });

    return false;
}

function initNewsScroller() {
  var overlapWidth = 12;
  var maxWidth = $("#news_scroller ul").outerWidth();
  var numSects = $("#news_scroller > ul > li").length;
  $("#news_scroller > ul > li").each(function(i) {
    if (i > 0) {
      var offsetLeft = maxWidth - ((numSects - i) * $(this).children("a").outerWidth());
      $(this).css({
        left: offsetLeft
      });
    }
    $(this).find(".news_scroll_arrows a").click(function() {
      clearInterval(_ticker);
      scrollNews($(this));
      return false;
    });
  });
}

function onClickNewsSliderButton(event) {
  clearInterval(_ticker);
  _ticker = setInterval(scrollNews, 5000);
  
  var overlapWidth = 12;
  var maxWidth = $("#news_scroller ul").outerWidth();
  var tabIndex = $(this).closest("ul").children("li").index($(this).parent("li"));
  
  if (tabIndex == 0) {
    $(this).closest("ul").children("li:eq(1)").animate({
      left: maxWidth - $(this).outerWidth()
    }, 500, 'swing', function() {
      $(this).removeClass("active");
      $(this).closest("ul").children("li:eq(0)").addClass("active");
    });
    $(this).closest("ul").children("li:eq(0)").animate({
      width: maxWidth
    }, 500, 'swing');
  }
  else {
    $(this).parent("li").animate({
      left: tabIndex * ($(this).outerWidth() - overlapWidth)
    }, 500, 'swing', function() {
      $(this).addClass("active");
      $(this).closest("ul").children("li:eq(0)").removeClass("active");
    });
    $(this).closest("ul").children("li:eq(0)").animate({
      width: $(this).outerWidth()
    }, 500, 'swing');
  }

  return false;
}

function onClickLightboxRemoveLink() {
    parentListItem = $(this).parent("li");
    parentListItem.hide();
    _lb.removeService($(this).parent().find("a").first());
    
    return false;
}

function updateFixedPosition() {
  $("#lightbox").css({
    "position": "absolute",
    "width": $(window).width() - 20,
    "top": parseInt($(window).scrollTop()) + parseInt($(window).height()) - $("#lightbox").outerHeight() + 'px'
  });
}

/*********
 * LIGHTBOX FUNCTIONS
 */

function Lightbox() {
    this.services = new Array();
    
    this.init = function() {
        if ($.browser.msie) {
          var iframe = $('<iframe id="ajaxIframe" name="ajaxIframe" border="0" style="visibility:hidden;width:0;height:0;">');
          $("#lightbox").append(iframe);
        }
        
        this.initServiceList();
        
        $("#lightbox-service-list").bind("serviceListUpdate", function(e) {
            _lb.updateSummaryView();
        });
        
        $("#lightbox-channels").find("a").each(function() {
            $(this).click(function() {
                $("#lightbox-channels").find("a").removeClass("active");
                $("#lightbox-channels-panels").children().hide();
                
                $(this).addClass("active");
                $("#" + this.id.replace("-channel-", "-form-")).show();
                
                return false;
            });
        });
    };
    
    this.initServiceList = function() {
      if (!$.browser.msie) {
        $.ajax({
            url:     "/gac/misc/lightbox.aspx",
            data:    "action=get",
            success: function(data) {
              _lb.processDataForGet(data);
            }
        });
      }
      else {
        var iform = $('<form>');
        iform.attr({
          "method": "post",
          "action": "/gac/misc/lightbox.aspx",
          "target": "ajaxIframe",
          "style": "visibility:hidden;width:0;height:0;"
        });
        $("#lightbox").append(iform);
        var lightboxActionHiddenField = $('<input name="action" type="text" value="get">');
        iform.append(lightboxActionHiddenField);
        $("#ajaxIframe").load(function() {
          _lb.processDataForGet($("#ajaxIframe").contents().children().text());
        });
        iform.submit();
      }
    };
    
    this.bindRemoveServiceLinks = function() {
        $("#lightbox-service-list a.remove-link").unbind('click');
        $("#lightbox-service-list a.remove-link").click(onClickLightboxRemoveLink);
    }
    
    this.updateServiceList = function() {
        $("#lightbox-service-list").empty();
        
        if (this.services.length > 1) {
            $("#lightbox-service-list-nocontent-message").hide();
            $("#lightbox-channels").show();
            $("#lightbox-form-contact").show();
            $("#lightbox-service-list-content").show();
        }
        else {
            $("#lightbox-channels").hide();
            $("#lightbox-channels-panels").children().hide();
            $("#lightbox-service-list-content").hide();
            $("#lightbox-service-list-nocontent-message").show();
        }
        
        for (i = 0; i < this.services.length/2; i++) {
            var serviceShortName = this.services[i*2];
            if (serviceShortName.length > 35) {
              serviceShortName = serviceShortName.substr(0, 35) + "...";
            }
            $("#lightbox-service-list").append('<li><div><a href="' + this.services[i*2+1] + '" title="' + this.services[i*2] + '" class="service-link">' + serviceShortName + '</a><a href="#" class="remove-link">Remove this service</a><div style="clear:both"></div></div></li>');
            $("#lightbox-service-list").trigger("serviceListUpdate");
        }
        this.updateSummaryView();
        this.bindRemoveServiceLinks();
    };
    
    this.updateSummaryView = function() {
      if ($("#lightbox .item-count span").length > 0) {
        $("#lightbox .item-count span").text(this.services.length / 2);
      }
      else {
        $("#lightbox .item-count").text(this.services.length / 2);
      }
    }
    
    this.addService = function(link) {
        inArrIndex = jQuery.inArray($(link).attr("title"), this.services);
        if (inArrIndex <= -1) {
            this.services.push($(link).attr("title"));
            this.services.push($(link).attr("href"));
            this.postToLightbox();
            $('#added_service_text').siblings('p').fadeOut('slow', function(){
              $("#added_service_text").fadeIn();
            });
        }
        else {
            alert("The service you are trying to add is already in your services box.");
        }
    }
    
    this.removeService = function(link) {
        inArrIndex = jQuery.inArray($(link).attr("title"), this.services);
        if (inArrIndex > -1) {
            this.services.splice(inArrIndex, 2);
            this.postToLightbox();
            if ($("#lightbox-add-handle").attr("title") == $(link).attr("title")) {
              $("#added_service_text").fadeOut('slow', function() {
                $("#added_service_text").siblings('p').fadeIn();
              });
            }
        }
        $("#lightbox-service-list").trigger("serviceListUpdate");
    }

    this.postToLightbox = function() {
      var servicesStr = "";
      for (var i = 0; i < this.services.length; i++) {
        if (this.services[i] != "") {
          servicesStr += '"' + $.URLEncode(this.services[i]) + '";';
        }
      }
      if (!$.browser.msie) {
        $.ajax({
          url: "/gac/misc/lightbox.aspx",
          data: "action=update&services=" + servicesStr,
          success: function(data) {
            _lb.processData(data);
          }
        });
      }
      else {
        var iform = $('<form>');
        iform.attr({
          "method": "post",
          "action": "/gac/misc/lightbox.aspx",
          "target": "ajaxIframe",
          "style": "visibility:hidden;width:0;height:0;"
        });
        $("#lightbox").append(iform);
        var lightboxValueHiddenField = $('<textarea name="services">' + servicesStr + '</textarea>');
        var lightboxActionHiddenField = $('<input name="action" type="text" value="update">');
        iform.append(lightboxValueHiddenField);
        iform.append(lightboxActionHiddenField);
        $("#ajaxIframe").load(function() {
          _lb.processData($("#ajaxIframe").contents().children().text());
        });
        iform.submit();
      }
    }
    
    this.processData = function (data) {
      var services = data.split(";");
      _lb.services = new Array();
      for (var i = 0; i < services.length / 2; i++) {
        if (services[i * 2] != "") {
          _lb.services.push($.URLDecode(services[i * 2].substr(1, services[i * 2].length - 2)));
          _lb.services.push($.URLDecode(services[i * 2 + 1].substr(1, services[i * 2 + 1].length - 2)));
        }
      }
      _lb.updateServiceList();
    }
    
    this.processDataForGet = function(data) {
      var services = data.split(";");
      try {
        for (var i = 0; i < services.length/2; i++) {
            if (services[i*2] != "") {
              _lb.services.push(services[i*2].substr(1, services[i*2].length-2));
              _lb.services.push(services[i*2+1].substr(1, services[i*2+1].length-2));
            }
        }
        if(jQuery.inArray($("#lightbox-add-handle").attr("title"), _lb.services) > -1)
        {
          $('#lightbox-add-handle').parent().parent().children("p").fadeOut('slow', function(){
            $('#added_service_text').fadeIn();
          });
        }
        if (_lb.services.length > 0) {
          $("#lightbox").show();
        }
        
        $("#lightbox-add-handle").unbind();
        $("#lightbox-add-handle").click(function() {
          _lb.addService(this);
          return false;
        });
      }
      catch (e) {}
      _lb.updateServiceList();
    }
    
}
