var image_swap;
var homeGalleryImages = new Array();
var homeGalleryGalleryIds = new Array();
var homeGalleryTimeout = 0;
var search_previous = "";

function ajax(parameters, output_element_id, timer_element_id, timer_innerHTML){
//function ajax(url, callback_function, return_xml){
    var http_request, response, i;
    
    var obj = document.getElementById(timer_element_id);
    
    // if have timer container then put in timer image
    if (obj != undefined){
        if (trim(timer_innerHTML) != ""){
            obj.innerHTML = timer_innerHTML;
        } else {
            obj.innerHTML = '<img src="./images/loading.gif" border="0" alt="please wait"/>';
        }
    }    
    
    var activex_ids = ['MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP','Microsoft.XMLHTTP'];

    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+...
        http_request = new XMLHttpRequest();
        
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) { // IE6 and older
        for (i = 0; i < activex_ids.length; i++) {
            try {
                http_request = new ActiveXObject(activex_ids[i]);
            } catch (e) {}
        }
    }
    if (!http_request) {
        alert('Unfortunately your browser doesn\'t support this feature.');
        return false;
    }

    http_request.onreadystatechange = function() {
        
        // if not ready yet
        if (http_request.readyState !== 4) {
            return;
        }
        
        // if ready, but not OK
        if (http_request.status !== 200) {
            alert('There was a problem with the request.(Code: ' + http_request.status + ')');
            return;
        }
        
        if (output_element_id != ""){
            document.getElementById(output_element_id).innerHTML = http_request.responseText;
        } else {
            eval(http_request.responseText);
        }
    };
    var r=parseInt(Math.random()*99999999); 
   // need to anchor GET to location.host 
    http_request.open('GET',"http://" + location.host + "/" +"_ajax.html?rand=" + r + "&" + parameters + "&timer_element_id=" + timer_element_id, true);
    http_request.send(null);
}

function trim(sString) {
    
    if (sString == undefined) return sString;
    if (sString.length == 0) return sString;
    
    while (sString.substring(0,1) == ' ') {
        sString = sString.substring(1, sString.length);
    }
    
    while (sString.substring(sString.length-1, sString.length) == ' ') {
        sString = sString.substring(0,sString.length-1);
    }
    
    return sString;
}

function doShowroomSearch(){
    // check if have criteria
    var search = document.getElementById('search').value;
    
    if (trim(search) == ""){
        alert("Please enter a suburb or postcode and try again.");
        return;
    }
    
    document.getElementById("frmMain").submit();
}

function showRowMore(branch_id){
    
    var linkMore = document.getElementById("linkMore" + branch_id);
    var rowMore = document.getElementById("rowMore" + branch_id);
    
    // if not visible show, otherwise hide
    if (rowMore.style.display == "none"){
        linkMore.innerHTML = linkMore.innerHTML.replace(/>More</, ">Hide<");
        rowMore.style.display = "";
    } else {
        linkMore.innerHTML = linkMore.innerHTML.replace(/>Hide</, ">More<");
        rowMore.style.display = "none";
    }
}

function scrollToMap(){
    var nPos = document.getElementById("map_anchor").offsetTop;
    window.scrollBy(0,nPos);
}

function showHomeGalleryImage(image_index, clear_timer, isAppear){
    var image_src = 'resources/images/' + homeGalleryImages[image_index];
    
    // if hiding then do fade and return
    if (!isAppear){
        doFade(image_index, clear_timer);
        return;
    }
    
    var hg_image = document.getElementById("hg_image");
    hg_image.style.backgroundImage = "url(" + image_src + ")";
    hg_image.onclick = function(){window.location='index.html?p=' + ig_page_id + '&id=' + homeGalleryGalleryIds[image_index]}
    
    //Effect.Appear('hg_image_div', { duration: 2.5 });
    fadeIn(2000, 'hg_image_div');
    
    if (clear_timer){
        clearTimeout(image_swap);
    } else {
        image_swap = setTimeout("showNextHomeGalleryImage(" + image_index + ")", homeGalleryTimeout);
        preloadNextImage(image_index);
    }
}

function preloadNextImage(current_index){
    current_index = current_index + 1;
    
    // if passed the end go back to first
    if (current_index > (homeGalleryImages.length - 1)){
        current_index = 0;
    }
    
    // load the image
    var myImage = new Image();
    var image_src = 'resources/images/' + homeGalleryImages[current_index];
    myImage.src = image_src;
}

function doFade(image_index, clear_timer){
    
    // fade out
    //Effect.Fade('hg_image_div', { duration: 1.2 });
    fadeOut(1200, 'hg_image_div');
    
    var x = setTimeout("showHomeGalleryImage(" + image_index + "," + clear_timer + ", true)", 1250);
}

function showNextHomeGalleryImage(current_index){
    current_index = current_index + 1;
    
    // if passed the end go back to first
    if (current_index > (homeGalleryImages.length - 1)){
        current_index = 0;
    }
    
    showHomeGalleryImage(current_index, false);
}

// set the opacity of the element (between 0.0 and 1.0) 
function setOpacity(level, element_id) {
  var obj = document.getElementById(element_id);
  
  try{
  obj.style.opacity = level;
  obj.style.MozOpacity = level;
  obj.style.KhtmlOpacity = level;
  obj.style.filter = "alpha(opacity=" + (level * 100) + ");";
  } catch (e){
  
  }
}

var steps = 20;       /* number of opacity intervals   */

function fadeIn(duration, element_id){
  for (i = 0; i <= 1; i += (1 / steps)) {
    setTimeout("setOpacity(" + i + ", '" + element_id + "')", i * duration);
  }
}

function fadeOut(duration, element_id) {
  for (i = 0; i <= 1; i += (1 / steps)) {
    setTimeout("setOpacity(" + (1 - i) + ", '" + element_id + "')", i * duration);
  }
  setTimeout("fadeIn()", duration);
}

function filterProduct(prid, cid, sid, sc){
	var prid = document.getElementById("price_range").value;
    var bid = document.getElementById("brand").value;
	var rid = document.getElementById("range").value;
	var p = document.getElementById("page_id").value;
	var url = window.location.href;
	var url = url.split("&");
	
	// if have search criteria then only do price range
	if (trim(sc) != ""){ 
	   window.location = url[0] + "&pr=" + prid + "&sc=" + sc;
    } else {
        window.location = url[0] + "&b=" + bid + "&r=" + rid + "&pr=" + prid;
    }
}

function setProductView(view_type){
    var url = window.location;
    
    // conv to string
    url = url + '';
    
    // remove any current setting
    url = url.replace(/&v=0/, "");
    url = url.replace(/&v=1/, "");
    
    // remove any irrelevant setting
    url = url.replace(/&v=/, "x=");
    
    // set new setting
    url = url + "&v=" + view_type;
    
    // go to new setting
    window.location = url;
}

function submitContactForm(){
    
    // do some client side validation
    var your_name = trim(document.getElementById('your_name').value);
    var email = trim(document.getElementById('email').value);
    var postcode = trim(document.getElementById('postcode').value);
    var enquiry = trim(document.getElementById('enquiry').value);
    
    if (your_name == ""){
        alert("Please enter your name and try again.");
        return false;
    }
    
    if (email == ""){
        alert("Please enter your email and try again.");
        return false;
    }
    
    if (postcode == ""){
        alert("Please enter your postcode and try again.");
        return false;
    }

    if (enquiry == ""){
        alert("Please enter an enquiry and try again.");
        return false;
    }
    
    if (enquiry.length > 3000){
        alert("Please ensure your enquiry is no longer than 3,000 characters and try again.");
        return false;
    }
    
    document.getElementById('submit_query').value = "true";
    document.getElementById('frmMain').submit();
}

function igHighlight(hotspot_id, isOver){
    if (isOver){
        document.getElementById('hs' + hotspot_id).style.border = '2px dashed orange';
        document.getElementById('icon' + hotspot_id).style.color = 'red';
        document.getElementById('lnk' + hotspot_id).style.color = '#0df';
    } else {
        document.getElementById('hs' + hotspot_id).style.border = '0';
        document.getElementById('icon' + hotspot_id).style.color = '#333';
        document.getElementById('lnk' + hotspot_id).style.color = '#fff';
    }
}

function igShowHideHotspots(){
    var obj = document.getElementById("ig_image");
    var children = obj.getElementsByTagName('div');
    var lnkShowHide = document.getElementById("lnkShowHideHotspots");
    var doHide;
    
    if (lnkShowHide.innerHTML == "Hide Hotspots"){
        lnkShowHide.innerHTML = lnkShowHide.innerHTML.replace(/Hide/, "Show");
        doHide = true;
    } else {
        lnkShowHide.innerHTML = lnkShowHide.innerHTML.replace(/Show/, "Hide");
        doHide = false;
    }
    
    for (i=0; i<children.length; i++){
        var strId = trim(children[i].id);
        
        if(strId.substr(0,4)=="icon"){
            if (doHide){
                document.getElementById(strId).style.display = "none";
            } else {
                document.getElementById(strId).style.display = "";
            }
        }
    }
}

function igResetRunning(){
    isRunning = false;
}

function igMoveToPrevious(){
    if (!isRunning){
        isRunning = true;
        setTimeout("igResetRunning()", 1100);
        currentPosition--;
        new Effect.Move('ig_image_container_inner', { x: 148, y: 0, transition: Effect.Transitions.sinoidal });
        
        if (numImages > 5){
            document.getElementById("btnScrollRight").style.display = "";
        } 
        
        if (currentPosition < 6){
            document.getElementById("btnScrollLeft").style.display = "none";
        }
    }
}

function igMoveToNext(){
    if (!isRunning){
        isRunning = true;
        setTimeout("igResetRunning()", 1100);
        currentPosition++;
        new Effect.Move('ig_image_container_inner', { x: -148, y: 0, transition: Effect.Transitions.sinoidal });
        
        if (currentPosition >= numImages){
            document.getElementById("btnScrollRight").style.display = "none";
        }
        
        document.getElementById("btnScrollLeft").style.display = "";
    }
}

function igShowProduct(item_no, hide_add){
    
    if (hide_add){
        var ha = "&ha=1";
    } else {
        var ha = "&ha=0";
    }
    
    window.open ("product_showroom.html?pu=1&i=" + item_no + ha, "","status=0,toolbar=0,menubar=0,resizable=0,scrollbars=1,height=500,width=800,top=50");
    return;
}

function igSelectAll(){
    var children = document.getElementById("products").getElementsByTagName('input');
    
    for (i=0; i<children.length; i++){
        children[i].checked = true;
    }
}

function igAddAllSelected(){
    
    var items = "";
    
    // get all checked products
	var chks = document.getElementsByName('chkItem');
    
    for (i=0; i<chks.length; i++){
        if (chks[i].checked){
            if (items != ""){
                items = items + ",";
            }
            items = items + '' + chks[i].id.substr(3,7);
        }
    }
    
    if (items != ""){
        addToMyList(items, false);
    } else {
        alert("Please tick at least one product first then try again.");
    }
}

function doMouseOverOutButton(obj, isOver){
    if (isOver){
        obj.style.backgroundColor = "#40689B";
        obj.style.color = "#fff";
    } else {
        obj.style.backgroundColor = "#fff";
        obj.style.color = "#555";
    }
}

function doProductSearch(){
    var obj = document.getElementById("search_criteria");
    
    if (trim(obj.value)==''){
        obj.value = "";
        alert("Please enter a product to search for and try again.");
    } else {
        document.getElementById('frmMain').submit();
    }
}

function doButtonClickOnEnter(e, btnId){
    if (e.keyCode == 13){
        try {
            var obj = document.getElementById(btnId);
            obj.focus();
            obj.click();
        } catch (e) {
        }
    }    
}

function doSubmitOnEnter(e){
    if (e.keyCode == 13){
        document.getElementById('frmMain').submit();
    }
}

function doEvalOnEnter(e, script_to_eval){
    if (e.keyCode == 13){
        eval(script_to_eval);
    }
}

function showPopup(popup_id){
    var obj = document.getElementById(popup_id);
    
    var w = obj.style.width;
    var h = obj.style.height;
    
    objWidth = w.substr(0,w.length - 2);
    objHeight = h.substr(0,h.length - 2);
    
    var xWithScroll = 0;
    var yWithScroll = 0;
    
    if (window.innerHeight && window.scrollMaxY) { // Firefox
        yWithScroll = window.innerHeight + window.scrollMaxY;
        xWithScroll = window.innerWidth + window.scrollMaxX;
    } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        yWithScroll = document.body.scrollHeight;
        xWithScroll = document.body.scrollWidth;
    } else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        yWithScroll = document.body.offsetHeight;
        xWithScroll = document.body.offsetWidth;
    }
    
    // get x position
    var x = (document.documentElement.clientWidth / 2) - (objWidth / 2);
    
    // get scroll top
    var sTop = document.body.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
    
    // get client height (Basically browser window height)
    var ch = (document.documentElement.clientHeight);
    
    // Place in centre of screen - irrespective where button is
    y = sTop + (ch/2) - (objHeight/2);
    
    obj.style.top = y + "px";
    obj.style.left = x + "px";
    
    // hide all combo boxes first
    var selects = document.getElementsByTagName("select");
    
    for (i = 0; i < selects.length; i++) {
        selects[i].style.display = "none";
    }
    
    // show the panel
    document.getElementById("popup_bg").style.visibility = "visible";
    document.getElementById("popup_bg").style.height = ((yWithScroll>ch?yWithScroll:ch) + 0) + "px";
    obj.style.visibility = "visible";
    
}

function getPostcode(){
    showPopup("popup");
    document.getElementById("postcode").focus();
    document.getElementById("postcode").select();
}

function doTCLogin(){
    //todo check that details entered
    
    document.getElementById('user_action').value = "tc_login";
    document.getElementById('frmMain').submit();
}

function updatePostcode(){
    
    // check entered postcode
    var tmp = trim(document.getElementById('postcode').value);
    
    if (tmp == ""){
        alert("Please enter a postcode and try again.");
        return;
    }
    
    document.getElementById('user_action').value = "set_postcode";
    document.getElementById('frmMain').submit();
}

function changePostcode(){
    document.getElementById('user_action').value = "change_postcode";
    document.getElementById('frmMain').submit();
}

function addToMyList(item_no, pu){
    if (pu){
        pu = "&pu=1";
    } else {
        pu = "&pu=0";
    }
    
    document.getElementById("popup").style.height = "85px";
    var obj = document.getElementById("popup_inner");
    obj.innerHTML = "<table><tr><td valign='middle' style='padding-right: 30px;'><img src='images/loading.gif'></td><td><b>Please wait...</b><td></tr></table>";
    showPopup("popup");
    //ajax("ajax_action=add_to_wishlist&i=" + item_no + pu, "temp", "", "");
    ajax("ajax_action=add_to_wishlist&i=" + item_no + pu, "", "", "");
    //alert("Item added to wishlist");
}

function closePopup(){
    document.getElementById("popup").style.visibility = "hidden";
    document.getElementById("popup_bg").style.visibility = "hidden";
}

function clearWishList(){
    if (confirm("Are you sure you wish to clear your wishlist?")){
        document.getElementById('user_action').value = "clear_wishlist";
        document.getElementById('frmMain').submit();
    }
}

function removeFromMyList(item_no){
    document.getElementById('user_action').value = "remove_from_wishlist";
    document.getElementById('user_var_1').value = item_no;
    document.getElementById('frmMain').submit();    
}

function printWishlist(){
    window.open ("wishlist.html?print=1","","status=0,toolbar=0,menubar=0,resizable=0,scrollbars=1,height=600,width=650,top=50");
    return;
}

function doTCChangePassword(){
    if (document.getElementById("current_password").value == ""){
        alert("Please enter your current password and try again.");
        return;
    }
    
    if (document.getElementById("new_password").value == ""){
        alert("Please enter a new password and try again.");
        return;
    }    
    
    if (document.getElementById("new_password").value != document.getElementById("confirm_password").value){
        alert("The 'New Password' and 'Confirm New Password' fields do not match.");
        return;
    }
    
    document.getElementById('user_action').value = "tc_change_password";   
    document.getElementById('frmMain').submit();    
}

function doTCRegsiter(){
    
    // check if entered account number and abn
    if (trim(document.getElementById('account_number').value)==""){
        alert('You must enter a Tradelink Account Number');
        return false;
    }
    
    if (trim(document.getElementById('abn').value)==""){
        alert('Please enter your ABN or "N/A" if you do not have one.');
        return false;
    }
    
    document.getElementById('user_action').value = "tc_register_first";
    document.getElementById('frmMain').submit();        
}

function doTCRegsiterSecond(){
    document.getElementById('user_action').value = "tc_register_second";
    document.getElementById('frmMain').submit();            
}

function doTCPasswordReset(){
    if (confirm("Are you sure you wish to reset your password?")){
        document.getElementById('user_action').value = "tc_password_reset";
        document.getElementById('frmMain').submit();        
    }
}

function doTCUpdateAccount(){
    document.getElementById('user_action').value = "tc_update_account";
    document.getElementById('frmMain').submit();
}

