var bolLtIE6 = false;
if($.browser.msie && (jQuery.browser.version < 6)) {bolLtIE6 = true}
var bolEqIE6 = false;
if($.browser.msie && (jQuery.browser.version == 6)) {bolEqIE6 = true}

// Returns value of a "value" property of a text box
function GetInputControlValue(id) {
	var ctrl = GetElementById(id);
	if (ctrl == null) {
		return null;
	}
	return ctrl.value;
}

// Returns value of a "checked" property of a checkbox
function GetCheckboxState(id) {
	var ctrl = GetElementById(id);
	if (ctrl == null) {
		return null;
	}
	return ctrl.checked;
}

// Returns html element by an id
function GetElementById(id) {
	return $("#" + id).get(0);
}

// Encodes a text string as a valid value of a URL.
function EncodeUrlValue(s) {
	var result = escape(s);
	result = result.replace(/\+/g, "%2B");
	result = result.replace(/%20/g, "+");
	result = result.replace(/\//g, "%2F");
	return result
}

// Get a variable from a cookie
function GetCookie(name) {
	var result = null;
	var arg = name + "=";
	var argLen = arg.length;
	var allCookies = document.cookie;
	var cookieLen = allCookies.length;
	var i = 0;
	while (i < cookieLen)
	{
		var j = i + argLen;
		if (allCookies.substring(i, j) == arg) {
			var endIndex = allCookies.indexOf (";", j);
			if (endIndex == -1) {
				endIndex = cookieLen;
			}
			result = unescape(allCookies.substring(j, endIndex));
			break;
		}
		i = allCookies.indexOf("; ", i);
		if (i == -1) {
			break;
		}
		i += 2;
	}
	return result;
}

// Save the specified variable to a cookie.
function SetCookie(name, value) {
	try
	{
		document.cookie = name + "=" + escape(value) + ";";
	}
	catch(e)
	{
	}
}

// Perform a quick search
function DoQuickSearch(searchPageBaseUrl, searchText, metaSpecialsOnly) {
	
	if (searchText == "") {
		return false;
	}
	var redirectUrl = searchPageBaseUrl;
	redirectUrl += (redirectUrl.indexOf("?") == -1)?"?":"&";
	var encodedSearchText = EncodeUrlValue(searchText);
	redirectUrl += "SearchText=" + encodedSearchText;
	if (metaSpecialsOnly == true) {
		redirectUrl += "&MetaSpecialsOnly=Y";
	}
	// Redirect to the search page
	DoRedirect(redirectUrl);
	return true;
}

// Redirects to the specified url
function DoRedirect(url) {
	window.location.href = url;
}

/*From http://www.sitepoint.com/article/standards-compliant-world*/
function externalLinks() 
{
	if (!document.getElementsByTagName) {
		return;
	}
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank";
	}
}

// Register Expandable Menu functions
function RegisterExpandableSectionMenu(menuId, cookieName) {
    RegisterExpandableMenu(menuId, cookieName, new ExpandSectionMenuUIStrategy());
}
function RegisterExpandableMiniBasket(menuId, cookieName) {
    RegisterExpandableMenu(menuId, cookieName, new ExpandMiniBasketUIStrategy());
}
var gExpandableMenus = new Array();
function RegisterExpandableMenu(menuId, cookieName, uiStrategy) {
    gExpandableMenus[menuId] = new ExpandableMenu(menuId, cookieName, uiStrategy);
}

// *** ExpandableMenu class ***
function ExpandableMenu(id, stateItemName, uiStrategy) {
    var me = this;
    // Properties
    this.id = id;
    this.uiStrategy = uiStrategy;
    this.stateValue = "";
    this.stateItemName = stateItemName;
    this.isRedundantSupported = (typeof (me.uiStrategy.RegisterRedundantOnClick) == "function") ? true : false;

    // Methods
    this.LoadState = function() {
        me.stateValue = GetCookie(me.stateItemName);
        if ((me.stateValue == null) || (me.stateValue == "")) {
            me.stateValue = me.uiStrategy.DefaultExpandedItemId;
        }
    }
    this.SaveState = function() {
        SetCookie(me.stateItemName, me.stateValue);
    }
    this.UpdateUI = function(useAnimation) {
        var visibleItemId = me.stateValue;
        var redundantVisibleStatus = false;
        if (visibleItemId == "none") {
            visibleItemId = "";
        }
        if (visibleItemId.indexOf("+") != -1) {
            var splitValue = visibleItemId.split("+");
            visibleItemId = splitValue[0];
            if (me.isRedundantSupported) {
                redundantVisibleStatus = (splitValue[1] == "show_redundant") ? true : false;
            }
        }
        me.uiStrategy.EnumerateAllItems(function(element) {
            var currentVisibleStatus = me.uiStrategy.GetVisibleStatus(element);
            var newVisibleStatus = (me.uiStrategy.GetItemId(element) == visibleItemId) ? true : false;
            if (newVisibleStatus != currentVisibleStatus) {
                if (newVisibleStatus && me.isRedundantSupported && !redundantVisibleStatus) {
                    me.uiStrategy.ShowRedundantItems(element, false, false);
                }
                me.uiStrategy.ShowItems(element, newVisibleStatus, useAnimation);
            }
            if (me.isRedundantSupported && newVisibleStatus) {
                var currentRedundantVisibleStatus = me.uiStrategy.GetRedundantVisibleStatus(element);
                var newRedundantVisibleStatus = (newVisibleStatus && redundantVisibleStatus) ? true : false;
                if (newRedundantVisibleStatus != currentRedundantVisibleStatus) {
                    me.uiStrategy.ShowRedundantItems(element, newRedundantVisibleStatus, useAnimation);
                }
            }
        });
    }
    this.OnClickHandler = function(element) {
        var currentVisibleStatus = me.uiStrategy.GetVisibleStatus(element);
        var newVisibleStatus = (!currentVisibleStatus);
        if (newVisibleStatus) {
            me.stateValue = me.uiStrategy.GetItemId(element);
        }
        else {
            me.stateValue = "none";
        }
        me.SaveState();
        me.UpdateUI(true);
    }
    this.ShowRedundantOnClickHandler = function(element) {
        if (me.isRedundantSupported) {
            me.stateValue += "+show_redundant";
            me.SaveState();
            me.UpdateUI(true);
        }
    }

    // Initialization
    me.LoadState();
    me.SaveState();
    me.UpdateUI(false);
    me.uiStrategy.RegisterOnClick(me.OnClickHandler);
    if (me.isRedundantSupported) {
        me.uiStrategy.RegisterRedundantOnClick(me.ShowRedundantOnClickHandler)
    }
}

// *** ExpandSectionMenuUIStrategy class ***
function ExpandSectionMenuUIStrategy() {
    var me = this;

    this.DefaultExpandedItemId = "";

    this.RegisterOnClick = function(callbackFunction) {
        $("ul.section-menu .action-opened").click(function() { callbackFunction(this); return false; });
        $("ul.section-menu .action").click(function() { callbackFunction(this); return false; });
    }
    this.GetContentItem = function(htmlElement) {
        var item = $(htmlElement).parent();
        if (item.get(0).id == "") {
            return null;
        }
        return item.children(".sub-section-menu");
    }
    this.GetItemId = function(htmlElement) {
        return $(htmlElement).parent().get(0).id;
    }
    this.GetVisibleStatus = function(htmlElement) {
        return me.GetContentItem(htmlElement).is(":visible");
    }
    this.ShowItems = function(htmlElement, isVisible, useAnimation) {
        var element = $(htmlElement);
		var element2 = $(".hide-element");
        var contentItem = me.GetContentItem(htmlElement);
        if (isVisible) {
            if (useAnimation)
                contentItem.slideDown("slow");
            else
                element2.show();
        }
        else {
            if (useAnimation)
                contentItem.slideUp("slow");
            else
                element2.hide();
        }
    }
    this.EnumerateAllItems = function(callbackFunction) {
        $("ul.section-menu .action").each(function() {
            callbackFunction(this);
        });
        $("ul.section-menu .action-opened").each(function() {
            callbackFunction(this);
        });
    }

}

// *** ExpandMiniBasketUIStrategy class ***
function ExpandMiniBasketUIStrategy() {
    var me = this;

    this.DefaultExpandedItemId = "basket-mini";

    this.RegisterOnClick = function(callbackFunction) {
        $("#basket-mini-header").click(function() { callbackFunction(this); return false; });
    }
    this.GetContentItem = function(htmlElement) {
        var contentItemId = htmlElement.id.replace(/-header$/, '');
        if (contentItemId == htmlElement.id) {
            // Incorrect header ID. It should be ended with "-header"
            return null;
        }
        return $("#" + contentItemId);
    }
    this.GetItemId = function(htmlElement) {
        return me.GetContentItem(htmlElement).get(0).id;
    }
    this.GetVisibleStatus = function(htmlElement) {
        return me.GetContentItem(htmlElement).is(":visible");
    }
    this.ShowItems = function(htmlElement, isVisible, useAnimation) {
        var contentItem = me.GetContentItem(htmlElement);
        if (isVisible) {
            if (useAnimation)
                contentItem.slideDown("slow");
            else
                contentItem.show();
        }
        else {
            if (useAnimation)
                contentItem.slideUp("slow");
            else
                contentItem.hide();
        }
    }
    this.EnumerateAllItems = function(callbackFunction) {
        $("#basket-mini-header").each(function() {
            callbackFunction(this);
        });
    }
}

// Display a product pop-up
function ShowProductAddInfo(pageURL)
{
	// center window on screen
	strOptions = 'height=600,width=600,location=no,menubar=no,scrollbars=yes,resizable=yes,status=no,top='
		+ (screen.availHeight/2 - 300) + ',left='
		+ (screen.availWidth/2 - 300);
	var hwndPopup;
	hwndPopup = window.open(pageURL, 'addInfo', strOptions);
	hwndPopup.focus();
	hwndPopup.moveTo((screen.availWidth/2 - 300), (screen.availHeight/2 - 300));
	hwndPopup.resizeTo(600, 600);
	return true;
}

// Display a pop-up with product full-size image
function ShowProductFullsizeImage(pageURL) {
    strOptions = 'location=no,menubar=no,scrollbars=no,resizable=no,status=no';
    if (navigator.appName == 'Opera')
        strOptions = 'width=100,height=100,' + strOptions;
    var hwndPopup = window.open(pageURL, "fullsizeImage", strOptions);
    hwndPopup.focus();
    return false;
}

// Resizes a pop-up window with product full-size image
function ResizeProductFullsizeImageWindow(picW, picH) {
    window.resizeTo(parseInt(picW), parseInt(picH));
    var innerW = 0;
    var innerH = 0;

    if (navigator.appName == 'Microsoft Internet Explorer') {
        innerW = self.document.documentElement.clientWidth;
        innerH = self.document.documentElement.clientHeight;
    }
    else {
        innerW = (typeof window.innerWidth == 'undefined') ? document.body.clientWidth : window.innerWidth;
        innerH = (typeof window.innerHeight == 'undefined') ? document.body.clientHeight : window.innerHeight;
    }

    var diffW = parseInt(picW) - parseInt(innerW);
    var diffH = parseInt(picH) - parseInt(innerH);

    var wndW = parseInt(picW) + parseInt(diffW) + 18;
    var wndH = parseInt(picH) + parseInt(diffH) + 60;

    var minWidth = 200;
    var minHeight = 200;
    wndW = wndW < minWidth ? minWidth : wndW;
    wndH = wndH < minHeight ? minHeight : wndH;

    window.resizeTo(wndW, wndH);
    moveTo((screen.availWidth / 2 - wndW / 2), (screen.availHeight / 2 - wndH / 2));
   }

function SetDisplayThumbnailCheckbox(isChecked) {
	if (top.leftlow == null)
		return;
	if (top.leftlow.document.getElementById('DisplayThumbnailCheck') != null)
		top.leftlow.document.getElementById('DisplayThumbnailCheck').checked = isChecked;
}

var g_arrAnchorButtons = new Array();

function AnchorButton(anchorHtmlElement)
{
	// Private variables
	var _anchorHtmlElement = anchorHtmlElement;
	var _spanObj = $("span", anchorHtmlElement);
	
	// Initialization
	_anchorHtmlElement.onmousedown = MouseDown;
	_anchorHtmlElement.onmouseup = MouseUp;
	
	// Implementation
	function MouseDown() {
		if (_anchorHtmlElement.setCapture) _anchorHtmlElement.setCapture();
		_spanObj.css("padding","2px 6px 1px 8px");
		return false;
	}
	function MouseUp() {
		if (_anchorHtmlElement.releaseCapture) _anchorHtmlElement.releaseCapture();
		_spanObj.css("padding","1px 7px 2px 7px");
		return true;
	}
}

function machblocks(selector, target_arr) {
	var hmax = 0;
	var wmax = 0;
	var count = 0;
	var module = 0;
	var obj = $(selector + " > li");
	if (bolLtIE6 || obj == undefined) {
		return false;
	}
	//$(selector).width("100%"); //for IE6 // replaced with css [selector] { zoom: 1 }
	var parentWidth = $(selector).width();
	var marginR = parseInt(obj.css("marginRight"));
	var paddingSum = parseInt(obj.css("paddingRight"))+parseInt(obj.css("paddingLeft"));
	var w2max = Math.floor(parentWidth/2 - marginR);
	var w3max = Math.floor(parentWidth/3 - marginR);
	var delta = 1;
	obj.each(
		function(){
			wmax=Math.max($(this).width(),wmax);
			for(i=0, imax=target_arr.length; i<imax; i++) {
				wmax=Math.max(($(target_arr[i], $(this)).width()+paddingSum),wmax);
				//$(target_arr[i], $(this)).css("borderColor","#FF0000");
				//$(target_arr[i], $(this)).css("borderWidth",1);
				//$(target_arr[i], $(this)).css("borderStyle","solid");
				//alert(target_arr[i]+"::::"+$(target_arr[i], $(this)).width());
			}
		}
	);
	if (wmax > w2max) {
		module = 1;
		obj.width(parentWidth - marginR - paddingSum - delta);
	} else if (wmax >= w3max && wmax <= w2max) {
		module = 2;
		obj.width(w2max - paddingSum - delta);
	} else {
		module = 3;
		obj.width(w3max - paddingSum - delta);
	}
	//alert(parseInt(obj.css("marginRight")));
	obj.each(
		function(){
			if ((++count)%module == 0) {
				$(this).css("marginRight",0);
			}
			hmax=Math.max($(this).height(),hmax);
		}
	);
	obj.height(hmax);
	//$(".product-list").css("paddingRight",0); //right padding removing
}

function GetDropDownItemCookieName(item) {
	return ("OSCARnet_ConsumablesFinder_" + item);
}

function RestoreSelectedItem(list) {
	return GetCookie(GetDropDownItemCookieName(list));
}
//Save selected index to cookie
function SetSelectedItem(list, item) {
	SetCookie(GetDropDownItemCookieName(list), item)
}

$(document).ready
(
	function() {
		externalLinks();
		if (!bolLtIE6) {
			$(".additional-info").click(function() {
				ShowProductAddInfo($(".additional-info").attr("href"));
				return false;
			});
			$("a.button").each(function() {
				g_arrAnchorButtons.push(new AnchorButton(this));
			});

			// Remove "visible-script-only" class to show all elements which should by visible only if client scripts allowed.
			$(".visible-script-only").removeClass("visible-script-only");
			// Hide all noscript elements (they should by visible only if client scripts are not allowed).
			$(".visible-noscript-only").hide();

		}
	}
);
