// Rig up the Search form functions (simple/advanced toggle and "Clear All" button)
(function () {

    var searchBox = $('search');


    if (searchBox) {

        // rig up switches for advanced and simple search-type; read/write the current value as cookie, and initialize the form according to the current setting.
        var searchSwitches = DOM.get('input[name="searchtype"]', searchBox),
            searchTypeNameSimple = 'simple',
            searchTypeNameAdvanced = 'advanced',
            searchTypeCookieName = 'search_type',
            searchTypeCookieValue = cookieU.getValue(searchTypeCookieName) || searchTypeNameSimple;

        for (var i = 0, input; (input = searchSwitches[i]); i++) {
            Event.add(input, 'click', function () {
                DOM[(this.value == 'simple') ? 'removeClass' : 'addClass'](searchBox, 'search-advanced');
                cookieU.set(searchTypeCookieName, this.value, '/');
                return true;
            });

            if (input.value == searchTypeCookieValue) {
                Event.fire(input, 'click');
                input.checked = true;
            }
        }

        // apply a clear-all form values behaviour for the "Clear all" button
        var clearBtn = DOM.get('div.clear-all a', searchBox)[0];
        if (clearBtn) {
            Event.add(clearBtn, 'click', function (e) {
                var inputs = DOM.get('input', searchBox),
                 queryInput;
                for (var i = 0, input; (input = inputs[i]); i++) {
                    if (input.type == 'checkbox') {
                        input.checked = false;
                    }
                    else if (!input.type || input.type == 'text') {
                        if (!queryInput) { queryInput = input; }
                        input.value = '';
                    }
                }
                queryInput && queryInput.focus();
                return false;
            });
        }


        // rig up collection sub menu toggling behaviour and set the appropriate initial states
        // based on cookie settings.
        var subCollections = DOM.get('fieldset.collections > ul ul', searchBox),
            collClosedClass = 'coll-closed',
            showTogglerText = 'Show',
            hideTogglerText = 'Hide',
            openCollectionCookieName = 'search_open',
            openCollectionsIdList = cookieU.getValue(openCollectionCookieName) || '';

        for (var j = 0, subCollElm; (subCollElm = subCollections[j]); j++) {
            var collElm = subCollElm.parentNode;
            collElm.collectionIdx = j + '';


            var togglerElm = DOM.makeElement('<a class="toggle-link" href="#">' + showTogglerText + '</a>');
            Event.add(togglerElm, 'click', function (e) {
                var li = this.parentNode,
                 isOpen = li.subCollectionsOpen = !li.subCollectionsOpen; // toggle the open status
                DOM[(isOpen) ? 'addClass' : 'removeClass'](this, 'toggle-link-open');
                DOM[(isOpen) ? 'removeClass' : 'addClass'](li, collClosedClass);
                this.innerHTML = (isOpen) ? hideTogglerText : showTogglerText;

                openCollectionsIdList = openCollectionsIdList.replace(li.collectionIdx, '') + ((isOpen) ? li.collectionIdx : '');
                cookieU.set(openCollectionCookieName, openCollectionsIdList, '/');

                return false;
            });

            DOM.insertBefore(togglerElm, subCollElm);

            if (openCollectionsIdList.indexOf(j) > -1) {
                Event.fire(togglerElm, 'click');
            }
            else {
                DOM.addClass(collElm, collClosedClass);
            }
        }

    }

    // Photo detail: "View all keywords" toggler  
    //hr1 15022010 fix js error.
    var CheckSearchKeywordElm = DOM.get('#searchbox fieldset.keywords');
    if (CheckSearchKeywordElm != null) {
        var searchkeywordElm = DOM.get('#searchbox fieldset.keywords')[0];
        if (searchkeywordElm) {
            var keywordsShowClass = 'all-keywords',
                showKwTogglerText = 'View all keywords',
                hideKwTogglerText = 'Hide keywords',
                togglerElm = DOM.makeElement('<a class="toggle-link" href="#">' + showKwTogglerText + '</a>');

            togglerElm.isOpen = true;

            Event.add(togglerElm, 'click', function (e) {
                this.isOpen = !this.isOpen;
                DOM[(this.isOpen) ? 'addClass' : 'removeClass'](this.parentNode, keywordsShowClass);
                DOM[(this.isOpen) ? 'addClass' : 'removeClass'](this, 'toggle-link-open');
                this.innerHTML = (this.isOpen) ? hideKwTogglerText : showKwTogglerText;
                // uncheck all "extra keyword" checkboxes when the user hides them
                if (!this.isOpen) { Array.forEach(DOM.get('.e input', searchkeywordElm), function (input) { input.checked = false; }); }
                return false;
            });

            DOM.appendChild(togglerElm, searchkeywordElm);
            Event.fire(togglerElm, 'click');
        }
    }

    // wraps buttons with a span tag on non mac browsers
    if (!/mac/i.test(navigator.platform)) // not for mac
    {
        var _btns = DOM.get('div.fi_btn input').concat(DOM.get('div.btn a')),
            i = 0, _btn;
        while (_btn = _btns[i++]) {
            var _span = document.createElement('span');
            _span.className = 'btnwrap';
            if (_btn.className) {
                var _btnClasses = _btn.className.split(/\s+/),
                j = _btnClasses.length;
                while (j--) {
                    _span.className += ' btnwrap_' + _btnClasses[j];
                }
            }
            DOM.replaceNode(_span, _btn);
            _span.appendChild(_btn);
        }
    }
})();


//// basic onContentLoaded utility functions
(function () {
    // fix the CSS background-image flicker bug in IE
    if (is_ie) { Event.add(window, 'load', function (e) { try { document.execCommand("BackgroundImageCache", false, true); } catch (err) { } }); }
    // Notify the CSS selectors that Javascript is up and running...
    // Remove the temporary <style id="noContentFlashHack" /> element created by the file removeflicker.js
    // (running this function here gives faster results than hooking it to the window.onload event.)
    var c = $('noContentFlashHack');
    if (c) { c.parentNode.removeChild(c); }
    DOM.addClass(document.body, 'js-active');
})();

if (window.fontSizer) {
    fontSizer.init();
}

if (window.popupLinks) {
    popupLinks.init();
}

if (window.boxRounder) {
    boxRounder.selectors = {
        'div.box': { handle: 'box' },
        'div.articleboxes div.item': { handle: 'item' }
    };
    boxRounder.init();
}
function getPhotoDetails(photoNumber, lang, FeatureNo, CDNO) {
    window.location.href = lang + "/Details/" + escape(photoNumber) + "?FeatureNo=" + FeatureNo + "&CDNO=" + CDNO;
}
function getId() {
    return document.getElementById('ctl00_drpLightbox').value;
}
function addPhotoToLightbox(photoNumber) {

    if (LoginUser != '') {
        if (checkLightbox()) {
            var requestParams = "photo_nr=" + escape(photoNumber) + "&lightbox_nr=" + getId();
            var qs = location.search.substring(1) + '';
            var path = location.search.substring(1) + "&cmd=add_to_lightbox&" + requestParams;
            if (qs.indexOf("photo_nr=") != -1) {
                qs = qs.replace("photo_nr=", "photo_nr11=");
                path = qs + "&cmd=add_to_lightbox&" + requestParams;
            }

            var httpRequest = getHttpRequest();

            httpRequest.open("post", "/Home.aspx", false);
            httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            httpRequest.send(path);

            var result13 = httpRequest.responseText.substring(httpRequest.responseText.lastIndexOf('~13hidden13') + 12, httpRequest.responseText.lastIndexOf('~13hidden13') + 13);

            if (httpRequest.responseText == "0") {
                if (confirm("Remove photo from lightbox?")) {
                    httpRequest.open("get", "/Home.aspx?cmd=delete_from_lightbox&" + requestParams, false);
                    httpRequest.send();
                }
            }
            else if (result13 == 1) {
                PhotoAddedMessageVisible(AddToLightboxMessage);
            }
            else {
                PhotoAddedMessageVisible(ExistsToLightboxMessage);
            }
            httpRequest.abort();
        }
        else {
        }
    }
    else {
        alert(LoginMesssage);
    }
}

//function addPhotoToCart( photoNumber )
//{    
//	var requestParams = "photo_nr=" + escape( photoNumber );	
//	var qs=location.search.substring(1) + '';	
//	var httpRequest = getHttpRequest();
//	var path =  location.search.substring(1) + "&cmd=add_to_cart&" + requestParams;
//	if(qs.indexOf("photo_nr=")!=-1)
//	{
//	    qs=qs.replace("photo_nr=","photo_nr11=");
//	    path=qs + "&cmd=add_to_cart&" + requestParams;
//	}	
//	try
//	{
//	httpRequest.open("post",Language + "/Default", false);

//	httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//	httpRequest.send(path);
//	}
//	catch(err)
//	{
//	    alert(err);
//	}	
//	var result13 = httpRequest.responseText.substring(httpRequest.responseText.lastIndexOf('~13hidden13') + 12, httpRequest.responseText.lastIndexOf('~13hidden13') + 13);	
//	
//	if (LoginUser != '')
//	{	   
//	    if(result13==1)
//	    {	
//	        PhotoAddedMessageVisible(AddToCartMessage);
//	        updatecartNumber();
//	    }
//	    else 
//	    {
//	        PhotoAddedMessageVisible(ExistsToCartMessage);
//	     }
//	}
//	else
//	{	
//        //bibin : 27-jun , change as now user can add photo to cart with login too        
//        var result131 = httpRequest.responseText.substring(httpRequest.responseText.lastIndexOf('~13hidden13') + 12, httpRequest.responseText.lastIndexOf('~13hidden13') + 13);	    
//	    if(result131==1)
//	    {
//	        PhotoAddedMessageVisible(AddToCartMessage);
//	        updatecartNumber();
//	    }
//	    else
//	    {
//	        PhotoAddedMessageVisible(ExistsToCartMessage);
//	    }
//	}	
//    httpRequest.abort();	
//}

function PhotoAddedMessageVisible(msg) {
    var div = document.getElementById('DivDetail');
    div.style.display = 'block';
    div.style.top = iebody.scrollTop + 50 + "px";
    var data = "<table width='100%' border='0'>";
    data = data + "<tr><td class='midheader' style='text-align:center; vertical-align: middle;' align='center'><strong>" + msg + "</strong></td></tr>";
    data = data + "</table>";
    div.innerHTML = data;
    timeID = setTimeout('PhotoAddedMessageHide()', 5000)
}
function PhotoAddedMessageHide() {
    if (document.getElementById('DivDetail')) {
        document.getElementById('DivDetail').style.display = 'none';
        return false;
    }
}
function updatecartNumber() {
    document.getElementById('ctl00_cartVal').innerHTML = parseInt(document.getElementById('ctl00_cartVal').innerHTML) + 1;
}

//function addPhotoToCartForProceed( photoNumber ) {    
//	var requestParams = "photo_nr=" + escape( photoNumber );
//	var qs=location.search.substring(1) + '';	
//	var httpRequest = getHttpRequest();
//	var path =  location.search.substring(1) + "&cmd=add_to_cart&" + requestParams;
//	if(qs.indexOf("photo_nr=")!=-1)
//	{
//	    qs=qs.replace("photo_nr=","photo_nr11=");
//	    path=qs + "&cmd=add_to_cart&" + requestParams;
//	}	
//	try
//	{	
//	httpRequest.open("post", Language + "/Default", + false);	
//	httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//	httpRequest.send(path);
//	}
//	catch(err)
//	{
//	    alert(err);
//	}	
//	var result13 = httpRequest.responseText.substring(httpRequest.responseText.lastIndexOf('~13hidden13') + 12,httpRequest.responseText.lastIndexOf('~13hidden13') + 13);	
//	if (LoginUser != '')
//	{	    
//	    if(result13==1)
//	    {	
//	        updatecartNumber();
//	    }
//	    else 
//	    {   
//	    }
//	}
//	else
//	{	
//	    alert(LoginMesssage);   
//	}
//	
//    httpRequest.abort();	
//}

function checkValue(txtValue) {
    var tValue = document.getElementById(txtValue);
    if (tValue.value == '') {
        alert('Please enter the pageno');
        return false;
    }
    return true;
}
function validateInt(txtValue) {
    switch (isInteger(txtValue.value)) {
        case true:
            return true;
            break;
        case false:
            txtValue.value = '';
            return false;
    }
}
function isInteger(s) {
    var i;
    if (isEmpty(s))
        if (isInteger.arguments.length == 1) return 0;
        else return (isInteger.arguments[1] == true);
    for (i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if (!isDigit(c)) return false;
    }
    return true;
}
function isEmpty(s) {
    return ((s == null) || (s.length == 0))
}
function isDigit(c) {
    return ((c >= "0") && (c <= "9"))
}


function checkNumber(oComp, sRule, nLength, fdecimal) {
    if (fdecimal == "" || typeof (fdecimal) == "undefined") {
        fdecimal = false;
    }

    //If the object is not specified return false
    if (typeof (oComp) == 'undefined' || oComp == null || oComp == '') {
        alert('Error: Input object not specified.');
        return false;
    }
    //If neither rule nor max length is specified, return false
    else if (typeof (sRule) == 'undefined' && typeof (nLength) == 'undefined') {
        alert('Error: No rule/maximum length for input object specified.');
        return false;
    }
    var noErrorFlg = true;

    //If object is specified and either of rule is specified,
    if (typeof (sRule) != 'undefined' && sRule != null) {
        var temp;
        sRule = sRule + "";
        var discardChars = false;
        if (sRule.length > 0 && sRule.charAt(0) == "~") {
            sRule = sRule.substring(1);
            discardChars = true;
        }
        if (typeof (oComp) == "undefined" || typeof (sRule) == "undefined")
            return false;

        for (var i = 0; i < oComp.value.length; i++) {
            temp = oComp.value.charAt(i);

            if ((!discardChars && sRule.indexOf(temp) == -1) || (discardChars && sRule.indexOf(temp) >= 0)) {
                //alert("Field disobeys entry rule.  Following are the valid characters:\n" + sRule);
                //alert("Invalid Character!");
                oComp.value = oComp.value.substring(0, i); // + (oComp.value.length > i ? oComp.value.substring(i+1):"");
                noErrorFlg = false;
                break;
            }
        }
    }
    if (nLength) {
        if (fdecimal) {
            nLength -= fdecimal;
            var dp = oComp.value.indexOf(".");
            var p1;
            var p2 = ""; ;
            if (dp >= 0) {
                p1 = oComp.value.substring(0, dp);
                p2 = oComp.value.substring(dp + 1);
            }
            else {
                p1 = oComp.value;
            }
            if (p1.length > nLength) {
                oComp.value = oComp.value.substring(0, nLength);
                return noErrorFlg;
            }
            for (var i = 0; i < p2.length; i++) {
                var ch = p2.charAt(i);
                if (ch < '0' || ch > '9') {
                    oComp.value = p1 + "." + p2.substring(0, i);
                    return noErrorFlg;
                }
            }
            if (p2.length > fdecimal) {
                oComp.value = p1 + "." + p2.substring(0, fdecimal);
            }
        }
        else if (oComp.value.length > nLength) {
            oComp.value = oComp.value.substring(0, nLength);
        }
    }
    return noErrorFlg;
}

function getPricingInfo(photoNumber, lang, FeatureNo, CDNO) {
    getPhotoDetails(photoNumber, lang, FeatureNo, CDNO);
}

function getHttpRequest() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        try {
            return new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            return new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
}
    
    

