/* Document ready starts here */
(function($) {
  $(document).ready(function() {
    $("body").addClass("javascript-on");
    /* All pages */
    $("#search input#queries_all_query").DefaultValue("Search this site");  // Set default value for searchbox
    $("ul.sf-menu").superfish();         // Dropdown menues (Primary Nav)
    addPrintLink("#content-icons");      // Print Icon added
    resizeText("#text-resizer");         // Resize Text
    
    /* Library Request Form */
    if ($("body#id7671").length) {
      var itemId = "list" + $.getURLParam("libraryitem");
      if ($("#library-request-list input[id='" + itemId + "']").length){
        $("#library-request-list input[id='" + itemId + "']").attr("checked", "checked");
      }
      $("#save_form_button").click(function(){
        var totalItems = "";
        $("#library-request-list input:checked").each(function(i){
          var itemTitle = $(this).attr("value");
          var countThis = i + 1;
          totalItems = totalItems + "(" + countThis + ") " + itemTitle + "  ";
        });
        $("#q7672_q9").attr("value", totalItems);
        $("#library-request-list").remove();
        $("#matrix-buttons input").click();
      });
    }
    // fix a-z links for resources for maori
    if ($("#id7910.maori").length){
      $(".az a").each(function(){
        var thisText = $(this).text();
        if ($("#maori-resource-list ." + thisText).length){
        } else {
          $(this).replaceWith(thisText);
        }  
      });
      if (location.search){
      } else {
        var newUrl = $(".az a:first").attr("href");
        $("#list-wrap").load(newUrl + " #browse-support-services-results", function(){
          addZebraStriping("#browse-support-services-results", "div.support-service:visible");
        });
      }
    }
    
    // fix a-z links for suppliers who hire
    if ($("#id13539").length){
      $(".az a").each(function(){
        var thisText = $(this).text();
        if ($("#suppliers-who-hire ." + thisText).length){
        } else {
          $(this).replaceWith(thisText);
        }  
      });
      var hireQuery = location.search.indexOf("result_13539_result_page");
      if (hireQuery == -1){
        var newUrl = $(".az a:first").attr("href");
        $("#list-wrap").load(newUrl + " #supplier-list", function(){
          addZebraStriping("#supplier-list", "div.supplier:visible");
        });
      }
    }

    /* Change support service search result number  */
    if ($("#id4955, #id3616, #id7910").length && $("#search-support-service p").length) {
      var realNumber = $(".support-service:visible").length;
      if (realNumber == 0){
        var newText = "No results found. Try searching again:";
      }
      else {
        var pText = $("#search-support-service p").text();
        var strippedText = pText.replace(/\d/g, "");
        var newText = realNumber + strippedText;
      }
      $("#search-support-service p").text(newText);
    }

    /* Information Centres by region page */
    if ($("body#id3893").length) {
      changeRegionInputFieldsToLinks();
      submitFormWhenRegionLinkClicked("#browse-info-centres-submit");
      ajaxInfoCentresFormSetup();
      addZebraStriping("#browse-info-centre-results", "div.info-centre");
      setupGoogleMaps();
    }

    /* Top level Information Centres by region page */
    if ($("body#id4846").length) {
      formatWekaRegions();
    }

    /* Suppliers by region pages */
    if ($("body#id3537, body#id7093, body#id7094").length) {
      formatWekaRegions();
    }

    /* Browse Support Services by services sub pages  */
    if ($("#info-centre-list").length) {
      addZebraStriping("#info-centre-list", "div.info-centre");
    }

    /* Supplier detail pages */
    if ($("#supplier-details").length) {
      wekaLocationsGoogleMaps();
      formatEquipmentSupplied();
    }

    /* Browse Supplier sub pages  */
    if ($("#supplier-list").length) {
      addZebraStriping("#supplier-list", "div.supplier");
    }

    /* Support Services by region page */
    if ($("body#id4032").length) {
      changeRegionInputFieldsToLinks();
      submitFormWhenRegionLinkClicked("#browse-support-services-submit");
      changeServiceInputFieldsToLinks();
      ajaxSupportServicesFormSetup();
      addZebraStriping("#browse-support-services-results", "div.support-service:visible");
      setupGoogleMaps();
    }

    /* Top level Support Services by region page */
    if ($("body#id4955").length) {
      formatWekaRegions();
      addZebraStriping("#search-support-services-results", "div.support-service:visible");
    }

    /* Weka Regions North Island / South Island pages  */
    if ($("#id5019, #id5020, #id4869, #id4871").length) {
      formatWekaRegions();
    }

    /* Browse National / Regional Support Services pages  */
    if ($("#browse-support-services-by-region").length) {
      setUpServicesList();
      changeServiceInputFieldsToLinks();
      addCurrentFiltersText();
      addZebraStriping("#browse-support-services-results", "div.support-service:visible");
    }

    /* Top level Support Services by services page */
    if ($("body#id3616").length) {
      formatSupportServicesByService();
      addZebraStriping("#search-support-services-results", "div.support-service:visible");
    }



    /* Search Support Services A-Z  */
    if ($("#id7910").length) {
      formatSupportServicesList();
      addZebraStriping("#browse-support-services-results", "div.support-service:visible");
      addZebraStriping("#search-support-services-results", "div.support-service:visible");
    }
    /* Browse Support Services by services sub pages  */
    if ($("#browse-support-services-by-support-service").length) {
      formatSupportServicesList();
      addZebraStriping("#browse-support-services-results", "div.support-service:visible");
    }

    /* Support Services details pages  */
    if ($("#support-service-details").length) {
      wekaLocationsGoogleMaps();
    }

    /* Support Services asset builder */
    if ($("body#id4183").length) {
      $("#show-map").click(function() { getMapCoordinates(); });
      formatSupportServicesAssetBuilder();
      processSupportServicesAssetBuilderOnSubmit();
    }

    /* Accessibility page */
    if ($("body#id3709").length) {
      setAutoUpdatingPreferences();
    }

   /* Support Services Section by category show current category being browsed */
   var curPageName = $(".current:last").text();
   // Following line removed as it causes an infinite loop on the National Support Services page
   // $("#li_container1").find("a:contains("+curPageName+")").css({"font-weight":"bold", "color":"#2881B5"});
  


  
  });
})(jQuery);



function formatWekaRegions() {
  // Put regions into 3 columns
  $("#weka-regions ul").makeacolumnlists({cols:2,colWidth:225,equalHeight:false,startN:1});
} // end of formatWekaRegions()

function formatEquipmentSupplied() {
  // Put equipment into 3 columns
  $("#equipment-supplied ul").makeacolumnlists({cols:3,colWidth:150,equalHeight:false,startN:1});
} // end of formatEquipmentSupplied()

function formatSupportServicesByService() {

  $("#support-service-services > ul").makeacolumnlists({cols:2,colWidth:225,equalHeight:false,startN:1});

} // end of formatSupportServicesByService()



function setUpServicesList() {

  // Show support services when link clicked
  $("#show-support-services").click(function() {
  
    $("#services-list").slideDown();
    $(this).hide();
    $("#hide-support-services").show();
  
  });
  
  // Hide support services when link clicked
  $("#hide-support-services").click(function() {
  
    $("#services-list").slideUp();
    $(this).hide();
    $("#show-support-services").show();
  
  });  

} // end setUpServicesList



function addCurrentFiltersText() {

  // If any filters were applied, then show text saying which filter was applied.
  if ($("#search-terms ul li").length) {
  
    var filterAppliedLi = $("#search-terms ul li");
    var filterSection = filterAppliedLi.parent("ul").parent("div").find("span").text();
    var textToInsert = ' / ' + filterSection + " / " + filterAppliedLi.text();
    $("#content h2").append(textToInsert);
  
  }

} // end addCurrentFiltersText


function formatSupportServicesList() {

  $("#support-services ul").makeacolumnlists({cols:2,colWidth:200,equalHeight:false,startN:1});

} // end formatSupportServicesList


function formatSupportServicesAssetBuilder() {

  // Format radio and checkbox metadata fields into 3 columns of equal height
  $("div.radio ul, div.checkbox ul").makeacolumnlists({cols:3,colWidth:200,equalHeight:false,startN:1});

  // Highlight current field in form
  $("input").focus(function() {
    $(this).parents("div.text, div.radio, div.checkbox").addClass("hasFocus");
  });
  $("input").blur(function() {
    $(this).parents("div.text, div.radio, div.checkbox").removeClass("hasFocus");
  });


} // end of formatSupportServicesAssetBuilder()


function autoPageUpdates() {

  var cookieName = "enable-auto-updates";

  if ($.cookie(cookieName) == "yes") {
    return true;
  } else {
    return false;
  }

} // end autoPageUpdates(




function setAutoUpdatingPreferences() {

  var cookieName = "enable-auto-updates";

  // If user chooses to not allow pages to automatically updates (e.g. via Ajax calls) then set a cookie.
  $("form#change-auto-updates-prefs").submit(function() {

    if ($("form#change-auto-updates-prefs input.radio:checked").val() == "0") {
      $.cookie(cookieName, 'no', { expires: 10000, path: '/' });
    } else {
      $.cookie(cookieName, 'yes', { expires: 10000, path: '/' });
    }

  });

  // When Accessibilty page loads, check the correct radio button for auto updating pages
  if (autoPageUpdates()) {
    $("form#change-auto-updates-prefs input.radio").attr("checked","");
    $("form#change-auto-updates-prefs input#updates-yes").attr("checked","checked");
  } else {
    $("form#change-auto-updates-prefs input.radio").attr("checked","");
    $("form#change-auto-updates-prefs input#updates-no").attr("checked","checked");
  }

} // end of setAutoUpdatingPreferences()



function processSupportServicesAssetBuilderOnSubmit() {

  $("#sq_commit_button").click(function() {
  
    populateLatLong();
    populateDynamicLocationsFields();

  });

} // end of processSupportServicesAssetBuilderOnSubmit()



function populateDynamicLocationsFields() {

  // Regions
  
  // Whichever regions are selected in the regions metadata field, select the same regions in the Dynamic Locations field
  $("#create-support-service-region ul li input:checked").each(function() {
  
    var selectedText = $(this).parent("li").find("label").text();
    $("#regions option").each(function() {

      var trimmedValue = $(this).html();
      while (trimmedValue.indexOf('&nbsp;') != -1) {
        trimmedValue = trimmedValue.replace(/&nbsp;/, " ");
      }
      if (trimmedValue == selectedText) {
        $(this).attr("selected","selected");
      }
    
    });
    
  });

  // Services
  
  // Whichever services are selected in the services metadata fields, select the same services in the Dynamic Locations field
  $("#create-support-service-service ul li input:checked").each(function() {
  
    var selectedText = $(this).parent("li").find("label").text();
    $("#services option").each(function() {

      var trimmedValue = $(this).html();
      while (trimmedValue.indexOf('&nbsp;') != -1) {
        trimmedValue = trimmedValue.replace(/&nbsp;/, " ");
      }
      if (trimmedValue == selectedText) {
        $(this).attr("selected","selected");
      }
    
    });
    
  });

} // end of populateDynamicLocationsFields()


function populateLatLong() {

  // When page is submitted, get latitude and longitude coordinates for the physical address
  $("#page_asset_builder_4183").submit(function() {

    var geocoder = null;
    var address = $("#metadata_field_text_3306_value").val() + ", " + $("#metadata_field_text_3308_value").val() + ", " + $("#metadata_field_text_3309_value").val();

    geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'address': address}, function(results, status) {

      if (status == google.maps.GeocoderStatus.OK) {
        if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

          // Set hidden latitude and longitude metadata fields
          $("#metadata_field_text_3317_value").attr("value", results[0].geometry.location.lat());
          $("#metadata_field_text_3316_value").attr("value", results[0].geometry.location.lng());

        } else {
//          alert("No results found");
        }
      } else {
//        alert("Geocode was not successful for the following reason: " + status);
      }

    });

  });
    
} // end of populateLatLong()


function changeRegionInputFieldsToLinks() {

  // Make regions unordered list into 3 columns of equal height
  $("#choose-region ul").makeacolumnlists({cols:3,colWidth:150,equalHeight:false,startN:1});

  // Wrap <a> tags around each region label
  $("#choose-region li label").each(function() {
    var htmlToInsert = "<a>" + $(this).text() + "</a>";
    $(this).html(htmlToInsert);
  });

  // Hide input fields and submit buttons
  $("#choose-region li input").hide();

} // end of changeRegionInputFieldsToLinks()



function submitFormWhenRegionLinkClicked(wrapper) {

  // hide input button
  $(wrapper).hide();

    // When region link is clicked, select this input field and submit the form
    $("#choose-region li label a").live("click", function() {
      $(this).parents("li").find("input").attr("checked","checked");
      $(wrapper + " input").click();
      return false;
    });
    
} // end submitFormWhenRegionLinkClicked()



function changeServiceInputFieldsToLinks() {

  // Hide input fields and submit buttons
  $("#support-services li input").hide();
  $("#support-services input:submit").hide();

  // Make services unordered list into 3 columns of equal height
  $("#services-list > ul").makeacolumnlists({cols:2,colWidth:225,equalHeight:false,startN:1});

  // Expand service type to show sub services
  $("#support-services h3 a").toggle(function() {
    $(this).parent("h3").parent("li").find("ul").slideDown();
  }, function() {
    $(this).parent("h3").parent("li").find("ul").slideUp();
  });

  // Wrap <a> tags around each services label
  $("#support-services li label").each(function() {
    var htmlToInsert = "<a>" + $(this).text() + "</a>";
    $(this).html(htmlToInsert);
  });

  // When service link is clicked, select this input field and submit the form
  $("#support-services li label a").live("click", function() {
    $(this).parent("label").parent("li").find("input").attr("checked","checked");
    $("#support-services input:submit").click();
    return false;
  });
  
  // Clear the service input fields
  $("#support-services input:checked").attr("checked","");

} // end of changeServiceInputFieldsToLinks()



function ajaxInfoCentresFormSetup() {

  // attach handler to form's submit event
  $("#browse-info-centres-submit input").click(function() {

    if (autoPageUpdates()) {

      var queryString = $('#search_page_3893').formSerialize() + "&SQ_DESIGN_NAME=blank";

      // get results by ajax and load dynamically into page without page reload
      $("#browse-info-centre-results-wrapper").load("http://enable.co.nz/weka/information-centres/by-region #browse-info-centre-results", queryString, 
        function() {
          addZebraStriping("#browse-info-centre-results", "div.info-centre");
          setupGoogleMaps();
        }); 

      // return false to prevent normal browser submit and page navigation
      return false;

    }

  });
  
}




function ajaxSupportServicesFormSetup() {

  // attach handler to form's submit event
  $("#browse-support-services-submit input").click(function() {

    var queryString = $('#search_page_4032').formSerialize() + "&SQ_DESIGN_NAME=blank";

    // get results by ajax and load dynamically into page without page reload
    $("#choose-service-and-results-wrapper").load("http://enable.co.nz/weka/support/by-region #choose-service-and-results", queryString, 
      function() {
        changeServiceInputFieldsToLinks();
        ajaxSupportServicesFormSetup();
        addZebraStriping("#browse-support-services-results", "div.support-service");
        setupGoogleMaps();
      }); 

    // return false to prevent normal browser submit and page navigation
    return false;

  });
  
}



function addZebraStriping(wrapper, internalDivs) {

  // Add background colour when mouse moves over divs
  $(wrapper + " " + internalDivs)
    .mouseover(function() {
        $(this).addClass("over");
      })
    .mouseout(function() {
      $(this).removeClass("over");
    });

  $(wrapper + " " + internalDivs + ":even").addClass("striped");

}



function resizeText(link) {

  $(link).toggle(
    function () {
      $("#content").css({"font-size":"1.5em"});
    },
    function () {
      $("#content").css({"font-size":"1em"});
    }
  );

}


function wekaLocationsGoogleMaps() {
  var contentString = $("#content h2:first").text();
  var lat = $("#latitude").text();
  var lng = $("#longitude").text();
  var latlng = new google.maps.LatLng(lat, lng);
  var myOptions = {
      zoom: 13,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("google-map"), myOptions);
  
  var infowindow = new google.maps.InfoWindow({
    content: contentString
  });

  var marker = new google.maps.Marker({
    position: latlng,
    map: map,
    title: ""
  });

  infowindow.open(map,marker);

} // end wekaLocationsGoogleMaps

function addPrintLink(el){ //adds the print button as it is useless without javascript

   $(el).find("a:first").after('<a id="printLink" href="#"><img src="/__data/assets/image/0013/3154/icon-print.gif" alt="Print"/></a>');
   $("#printLink").click(function(){
      window.print();
   });
   
} //end addPrintLink








/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
      
var tb_pathToImage = "http://matrix.enable.co.nz/_designs/weka/images/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
  tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
  imgLoader = new Image();// preload image
  imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
  $(domChunk).click(function(){
  var t = this.title || this.name || null;
  var a = this.href || this.alt;
  var g = this.rel || false;
  tb_show(t,a,g);
  this.blur();
  return false;
  });
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

  try {
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
      $("body","html").css({height: "100%", width: "100%"});
      $("html").css("overflow","hidden");
      if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
        $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }else{//all others
      if(document.getElementById("TB_overlay") === null){
        $("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
        $("#TB_overlay").click(tb_remove);
      }
    }
    
    if(tb_detectMacXFF()){
      $("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
    }else{
      $("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
    }
    
    if(caption===null){caption="";}
    $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
    $('#TB_load').show();//show loader
    
    var baseURL;
     if(url.indexOf("?")!==-1){ //ff there is a query string involved
      baseURL = url.substr(0, url.indexOf("?"));
     }else{ 
        baseURL = url;
     }
     
     var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
     var urlType = baseURL.toLowerCase().match(urlString);

    if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
        
      TB_PrevCaption = "";
      TB_PrevURL = "";
      TB_PrevHTML = "";
      TB_NextCaption = "";
      TB_NextURL = "";
      TB_NextHTML = "";
      TB_imageCount = "";
      TB_FoundURL = false;
      if(imageGroup){
        TB_TempArray = $("a[@rel="+imageGroup+"]").get();
        for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
          var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
            if (!(TB_TempArray[TB_Counter].href == url)) {            
              if (TB_FoundURL) {
                TB_NextCaption = TB_TempArray[TB_Counter].title;
                TB_NextURL = TB_TempArray[TB_Counter].href;
                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
              } else {
                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                TB_PrevURL = TB_TempArray[TB_Counter].href;
                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
              }
            } else {
              TB_FoundURL = true;
              TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);                     
            }
        }
      }

      imgPreloader = new Image();
      imgPreloader.onload = function(){   
      imgPreloader.onload = null;
        
      // Resizing large images - orginal by Christian Montoya edited by me.
      var pagesize = tb_getPageSize();
      var x = pagesize[0] - 150;
      var y = pagesize[1] - 150;
      var imageWidth = imgPreloader.width;
      var imageHeight = imgPreloader.height;
      if (imageWidth > x) {
        imageHeight = imageHeight * (x / imageWidth); 
        imageWidth = x; 
        if (imageHeight > y) { 
          imageWidth = imageWidth * (y / imageHeight); 
          imageHeight = y; 
        }
      } else if (imageHeight > y) { 
        imageWidth = imageWidth * (y / imageHeight); 
        imageHeight = y; 
        if (imageWidth > x) { 
          imageHeight = imageHeight * (x / imageWidth); 
          imageWidth = x;
        }
      }
      // End Resizing
      
      TB_WIDTH = imageWidth + 30;
      TB_HEIGHT = imageHeight + 60;
      $("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>");    
      
      $("#TB_closeWindowButton").click(tb_remove);
      
      if (!(TB_PrevHTML === "")) {
        function goPrev(){
          if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
          return false; 
        }
        $("#TB_prev").click(goPrev);
      }
      
      if (!(TB_NextHTML === "")) {    
        function goNext(){
          $("#TB_window").remove();
          $("body").append("<div id='TB_window'></div>");
          tb_show(TB_NextCaption, TB_NextURL, imageGroup);        
          return false; 
        }
        $("#TB_next").click(goNext);
        
      }

      document.onkeydown = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        } else if(keycode == 190){ // display previous image
          if(!(TB_NextHTML == "")){
            document.onkeydown = "";
            goNext();
          }
        } else if(keycode == 188){ // display next image
          if(!(TB_PrevHTML == "")){
            document.onkeydown = "";
            goPrev();
          }
        } 
      };
      
      tb_position();
      $("#TB_load").remove();
      $("#TB_ImageOff").click(tb_remove);
      $("#TB_window").css({display:"block"}); //for safari using css instead of show
      };
      
      imgPreloader.src = url;
    }else{//code to show html
      
      var queryString = url.replace(/^[^\?]+\??/,'');
      var params = tb_parseQuery( queryString );

      TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
      TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
      ajaxContentW = TB_WIDTH - 30;
      ajaxContentH = TB_HEIGHT - 45;
      
      if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window    
          urlNoQuery = url.split('TB_');
          $("#TB_iframeContent").remove();
          if(params['modal'] != "true"){//iframe no modal
            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
          }else{//iframe modal
          $("#TB_overlay").unbind();
            $("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
          }
      }else{// not an iframe, ajax
          if($("#TB_window").css("display") != "block"){
            if(params['modal'] != "true"){//ajax no modal
            $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
            }else{//ajax modal
            $("#TB_overlay").unbind();
            $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); 
            }
          }else{//this means the window is already up, we are just loading new content via ajax
            $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
            $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
            $("#TB_ajaxContent")[0].scrollTop = 0;
            $("#TB_ajaxWindowTitle").html(caption);
          }
      }
          
      $("#TB_closeWindowButton").click(tb_remove);
      
        if(url.indexOf('TB_inline') != -1){ 
          $("#TB_ajaxContent").append($('#' + params['inlineId']).children());
          $("#TB_window").unload(function () {
            $('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
          });
          tb_position();
          $("#TB_load").remove();
          $("#TB_window").css({display:"block"}); 
        }else if(url.indexOf('TB_iframe') != -1){
          tb_position();
          if($.browser.safari){//safari needs help because it will not fire iframe onload
            $("#TB_load").remove();
            $("#TB_window").css({display:"block"});
          }
        }else{
          $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
            tb_position();
            $("#TB_load").remove();
            tb_init("#TB_ajaxContent a.thickbox");
            $("#TB_window").css({display:"block"});
          });
        }
      
    }

    if(!params['modal']){
      document.onkeyup = function(e){   
        if (e == null) { // ie
          keycode = event.keyCode;
        } else { // mozilla
          keycode = e.which;
        }
        if(keycode == 27){ // close
          tb_remove();
        } 
      };
    }
    
  } catch(e) {
    //nothing here
  }
}

//helper functions below
function tb_showIframe(){
  $("#TB_load").remove();
  $("#TB_window").css({display:"block"});
}

function tb_remove() {
  $("#TB_imageOff").unbind("click");
  $("#TB_closeWindowButton").unbind("click");
  $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
  $("#TB_load").remove();
  if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
    $("body","html").css({height: "auto", width: "auto"});
    $("html").css("overflow","");
  }
  document.onkeydown = "";
  document.onkeyup = "";
  return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
  if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
  }
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
  var de = document.documentElement;
  var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
  var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
  arrayPageSize = [w,h];
  return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


