﻿function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function ValidateQty(textboxId, iconId, valmes, MaxValue) {
    var qnty = $("#" + textboxId).val();

    if (!qnty || qnty == '') {
        $("#" + iconId).show();
        $("#" + valmes).hide();
        return false;
    }
    else if (parseInt(qnty) > MaxValue || parseInt(qnty) == 0 || !is_int(qnty)) {
        $("#" + iconId).hide();
        $("#" + valmes).show();
        return false;
    }
    else {
        $("#" + iconId).hide();
        return true;
    }
}

function is_int(value) {
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        return false;
    }
}

function ValidateSearch(valimg) {
    var searchString = $("#term").val();
    if (IsBlank(searchString)){
        $("#"+ valimg).css("display","block");
        return false;
    }
    else {
        if (HasInvalidChar(searchString)) {
            $("#" + valimg).css("display", "block");
            return false;
        }
        $("#" + valimg).css("display", "none");
        return true;
    }
}

function IsBlank(str) {
    return (!str || /^\s*$/.test(str));
}

function HasInvalidChar(str) {
    var iChars = '+-&|!(){}[]^"~*?:' + "\\"; 

    for (var i = 0; i < str.length; i++) {
        if (iChars.indexOf(str.charAt(i)) != -1) {
            return true;
        }
    }
    return false
}



function ViaValidation(valFunction, CallbackFunction) {
    if (valFunction() == false) {
        return false;
    }
    else {
        CallbackFunction();
    }
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }

var cartbounce

function showBasket() {
    if ($('#MCOpenClose').hasClass('opened')) { clearTimeout(cartbounce); }
    else {cartbounce = setTimeout("TogglePanel('MCOpenClose', 'MCStretch', 800, 'CLOSE BASKET', 'OPEN BASKET');", 20000); }
    TogglePanel('MCOpenClose', 'MCStretch', 800, 'CLOSE BASKET', 'OPEN BASKET'); 
}
function bounceBasket() {
    TogglePanel('MCOpenClose', 'MCStretch', 800, 'CLOSE BASKET', 'OPEN BASKET');
    cartbounce = setTimeout("TogglePanel('MCOpenClose', 'MCStretch', 800, 'CLOSE BASKET', 'OPEN BASKET');", 8000);
    
}
function showWishlist() {
    TogglePanel('MWOpenClose', 'MWStretch', 800, 'CLOSE', 'OPEN');
}

function showMailOrder() {
    if ($('#MMOpenClose').hasClass('opened')) { clearTimeout(cartbounce); }
    else { cartbounce = setTimeout("TogglePanel('MMOpenClose', 'MMStretch', 800, 'CLOSE BASKET', 'OPEN BASKET');", 20000); }
    TogglePanel('MMOpenClose', 'MMStretch', 800, 'CLOSE BASKET', 'OPEN BASKET'); 
}

function TogglePanel(triggerid, panelid, speed, openedtext, closedtext) {
    $('#' + triggerid).toggleClass('opened closed');
    $('#' + panelid).slideToggle(speed);    
    if (openedtext.length > 0) {
        $('#' + triggerid + '.opened').html(openedtext);
    }
    if (closedtext.length > 0) {
        $('#' + triggerid + '.closed').html(closedtext);
    }
}

function fadeoutin(action, setid, setcount, buttonid, hidden, altbuttonid) {

    if ($('#' + buttonid).attr('disabled') != 'disabled') {
        
        var currentset = parseInt($('#' + hidden).val());
        var settofade = setid + "_" + currentset;
        var nextsettofade = setid + "_" + (currentset + 1);
        var previoussettofade = setid + "_" + (currentset - 1);
        $('#' + altbuttonid).attr('disabled', 'disabled');
        $('#' + buttonid).attr('disabled', 'disabled');
        if (action == 'next') {
            if (currentset < setcount) {
                $('#' + settofade).fadeOut(500, function () {
                    currentset++;
                    if (currentset < setcount) {
                        $('#' + buttonid).removeAttr('disabled')
                    }
                    ($('#' + hidden)).val(currentset);
                    $('#' + nextsettofade).fadeIn(500);
                })
            }
            if (currentset >= 1) {
                $('#' + altbuttonid).removeAttr('disabled')
            }
        }
        if (action == 'previous') {
            if (currentset > 1) {
                $('#' + settofade).fadeOut(500, function () {
                    currentset--;
                    if (currentset > 1) {
                        $('#' + buttonid).removeAttr('disabled')
                    }
                    $('#' + hidden).val(currentset);
                    $('#' + previoussettofade).fadeIn(500);
                })
            }
            if (currentset <= setcount) {
                $('#' + altbuttonid).removeAttr('disabled')
            }
        }
    }
}

function showZoom(imageid) {
    
    if (!imageid) {
        imageid = _currentImage;
    }

    $('#pd_info').fadeTo(500, 0.5)
    $('#' + imageid).fadeOut(250, function () {
        $('#pd_zoomcont').effect("scale", { percent: 191, direction: 'horizontal', content: 'content' }, 500, function () {
            $('#pd_zoomcont').css('width', '582px');
            var params = {
                bgcolor: "#fff",
                wmode: "transparent"
            };
            swfobject.embedSWF(BASE_APP_URL + "Images/flash/CSProductZoomer_v1.swf?query=" + BASE_APP_URL + _imageData, "pd_flashZoom", "582", "408", "9.0.0", false, false, params);
        })
    })
}

var _currentImage;
var _imageData;
var _ZoomZoomClientId;

function closeZoom(imageid) {
    if (!imageid) {
        imageid = _currentImage;
    }
    $("#pd_flashZoomContainer").html('<div id="pd_flashZoom"></div>')
    $('#pd_info').fadeTo(500, 1);
    $('#pd_zoomcont').effect("scale", { percent: 52, direction: 'horizontal', content: 'content' }, 500, function () {
        $('#' + imageid).fadeIn(250);
        $('#pd_zoomcont').css('width', '306px');
        $('#pd_zoomcont').fadeOut(100);        
    })
}

function ResetCarousel(hidden) {
    MM_findObj(hidden).value = 1;
}

function showtab(namingcontainer, tab, tabcount) {
    var tabclicked = namingcontainer + '_tab_' + tab;
    var tabtoshow = namingcontainer + '_tabc_' + tab;
    var objtabs;
    for (i = 1; i < (tabcount + 1); i++) {
        try {
            var tabs = namingcontainer + '_tab_' + i
            var tabtoclear = namingcontainer + '_tabc_' + i
            objtabs = MM_findObj(tabs);
            if (objtabs) {
                objtabs.className = '';
                MM_findObj(tabtoclear).style.display = "none";
            }
        } catch (e) { }
    }
    MM_findObj(tabclicked).className += ' active';
    MM_findObj(tabtoshow).style.display = "";
    return false;
}

var _countryId;
function IsCheckBoxChecked(container, validation) {
    var checkBoxes = $("#" + container + " input:checked");
    if (checkBoxes.length == 0) {
        $("#" + validation).fadeIn();
        _IsValid = false;
    }
    else {
        _countryId = checkBoxes.parent().prev().val();
        $("#" + validation).fadeOut();
        _IsValid = true;
    }
}

function ValidateDeliveryCO() {
    var pnl = $("#pnlNoDeliveryOptions")
    if (pnl) {
        if (pnl.is(':visible')) {
            _IsValid = false
        }
        else {
            _IsValid = true
        }
    }
    else {
        _IsValid = true
    }

}

function printit() {
    if (window.print) {
        window.print();
    } else {
        var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
        document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
        WebBrowser1.ExecWB(6, 1); //Use a 1 vs. a 2 for a prompting dialog box    WebBrowser1.outerHTML = "";  
    }
}




/* Modals */
function showHint(hintcid) {
    $('#' + hintcid).fadeIn(300);
    $('#' + hintcid).mouseleave(function () {
        $('#' + hintcid).fadeOut(300);
    });
}
function showModal(modalcid) {
    $('#' + modalcid).fadeIn(300);
}
function closeModal(modalcid) {
    $('#' + modalcid).fadeOut(300);
}
function PositionModal(modalid, modalcont, height) {
    var windowheight = MM_findObj(modalcont).offsetHeight;
    //var modalheight = MM_findObj(modalid).offsetHeight;
    var remainder = windowheight - height;
    remainder = remainder / 2 - (height / 2);
    //new Effect.Morph(MM_findObj(modalid), {style: 'margin-top:'+remainder+"px",duration: 0.3});
    MM_findObj(modalid).style.marginTop = remainder + "px";
}

function openPopup(destination, options, name) {
    try {
        window.open(destination, name, options);
    } catch (e) {
    }
}

function format(str) {
    for (i = 1; i < arguments.length; i++) {
        str = str.replace('{' + (i - 1) + '}', arguments[i]);
    }
    return str;
}


function ShowQuickBuy(productId, path, categoryType) {
    var parameters = "{'ProductId': {0}, 'purchasePath': '{1}', 'categoryType': {2}, 'updateOptions': {3}, 'cartRowId': {4}}"
    var data = format(parameters, productId, path, categoryType, false, 0);

    GetControl(data, 'Service/BasketService.asmx/GetQuickBuyControl', function (response) {
        $("#quickbuy").html(response);
        $('#quickbuy').jqmShow();
    });
}

function UpdateOptionsWithQuantity(productId, path, categoryType, cartRowId, selectedOptions, quantity) {
    var parameters = "{'ProductId': {0}, 'purchasePath': '{1}', 'categoryType': {2}, 'updateOptions': {3}, 'cartRowId': {4}, 'buyingOptions': '{5}', 'quantity': {6}}"
    var data = format(parameters, productId, path, categoryType, true, cartRowId, selectedOptions, quantity);

    GetControl(data, 'Service/BasketService.asmx/GetQuickBuyControlWithBuyingOptionsAndQuantity', function (response) {
        $("#quickbuy").html(response);
        $('#quickbuy').jqmShow();
    });
}

function UpdateQuickBuy(productId, path, categoryType, buyingOptions, updateOptions, cartRowId, quantity) {
    var parameters = "{'ProductId': {0}, 'purchasePath': '{1}', 'categoryType': {2}, 'buyingOptions': '{3}', 'updateOptions': {4}, 'cartRowId': {5}, 'quantity': {6}}"
    var data = format(parameters, productId, path, categoryType, buyingOptions, Boolean(updateOptions), cartRowId, quantity);

    GetControl(data, 'Service/BasketService.asmx/GetQuickBuyControlWithBuyingOptionsAndQuantity', function (response) {
        $("#quickbuy").html(response);
    });
}


function HideQuickBuy() {
        $('#quickbuy').jqmHide();
}

function GetControlNoData(serviceURI, onSuccess, params) {
    $.ajax({
        type: "POST",
        cache: false,
        url: BASE_APP_URL + serviceURI,
        dataType: 'html',
        success: function (msg) {
            onSuccess(msg, params);
        },
        error: function (a, b, c) {
            
        }
    });
}

function GetControl(data, serviceURI, onSuccess) {
    $.ajax({
        type: "POST",
        cache: false,
        data: data,
        url: BASE_APP_URL + serviceURI,
        dataType: "html",
        contentType: "application/json; charset=utf-8",
        dataFilter: function (data, datatype) {            
            return data.replace('{"d":null}', '');
        },
        success: function (msg) {
            onSuccess(msg);
        },
        error: function (a, b, c) {
           
        }
    });
}

function SelectedImageChanged(productId, width, height, buttonclicked) {
    var parameters = "{'productId': {0}, 'width': {1}, 'height': {2}}";
    var data = format(parameters, productId, width, height);
    $.ajax({
        type: "POST",
        cache: true,
        data: data,
        url: BASE_APP_URL + 'Service/ImageService.asmx/GetImageInfo',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (result) {

            $('#pd_mainimg').children('img').attr('src', result.d.MainImageLink);
            $('.altimage').removeClass('active');
            buttonclicked.addClass('active');

            if (result.d.NoOfZoomLvls > 2) {
                if ($('#pd_zoomcont').css('display') == 'none') {
                    //need to show the zoom button
                    var lb = $('#' + _ZoomZoomClientId);
                    if (lb) {
                        lb.css('display', 'block')
                    }
                    _imageData = result.d.SwfObjectData
                }
                else {
                    $("#pd_flashZoomContainer").html('<div id="pd_flashZoom"></div>')
                    var params = {
                        bgcolor: "#fff"
                    };
                    _imageData = result.d.SwfObjectData
                    swfobject.embedSWF(BASE_APP_URL + "Images/flash/CSProductZoomer_v1.swf?query=" + BASE_APP_URL + result.d.SwfObjectData, "pd_flashZoom", "582", "408", "9.0.0", false, false, params);
                }
            }
            else {
                //need to remove the zoom button
                var lb = $('#' + _ZoomZoomClientId);
                if (lb) {
                    lb.css('display', 'none')    
                }
                if ($('#pd_zoomcont').css('display') != 'none') {
                    closeZoom(null);
                }
            }
        },
        error: function (a, b, c) {
            alert("there has been a script issue when selected image changed")
        }
    });
}


/*
* jqModal - Minimalist Modaling with jQuery
*   (http://dev.iceburg.net/jquery/jqModal/)
*
* Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
* 
* $Version: 03/01/2009 +r14
*/
(function ($) {
    $.fn.jqm = function (o) {
        var p = {
            overlay: 80,
            overlayClass: 'mdlbg',
            closeClass: 'mdlclose',
            trigger: '.jqModal',
            ajax: F,
            ajaxText: '',
            target: F,
            modal: F,
            toTop: F,
            onShow: F,
            onHide: F,
            onLoad: F
        };
        return this.each(function () {
            if (this._jqm) return H[this._jqm].c = $.extend({}, H[this._jqm].c, o); s++; this._jqm = s;
            H[s] = { c: $.extend(p, $.jqm.params, o), a: F, w: $(this).addClass('jqmID' + s), s: s };
            if (p.trigger) $(this).jqmAddTrigger(p.trigger);
        });
    };

    $.fn.jqmAddClose = function (e) { return hs(this, e, 'jqmHide'); };
    $.fn.jqmAddTrigger = function (e) { return hs(this, e, 'jqmShow'); };
    $.fn.jqmShow = function (t) { return this.each(function () { t = t || window.event; $.jqm.open(this._jqm, t); }); };
    $.fn.jqmHide = function (t) { return this.each(function () { t = t || window.event; $.jqm.close(this._jqm, t) }); };

    $.jqm = {
        hash: {},
        open: function (s, t) {
            var h = H[s], c = h.c, cc = '.' + c.closeClass, z = (parseInt(h.w.css('z-index'))), z = (z > 0) ? z : 3000, o = $('<div></div>').css({ height: '100%', width: '100%', position: 'fixed', left: 0, top: 0, 'z-index': z - 1, opacity: c.overlay / 100 }); if (h.a) return F; h.t = t; h.a = true; h.w.css('z-index', z);
            if (c.modal) { if (!A[0]) L('bind'); A.push(s); }
            else if (c.overlay > 0) h.w.jqmAddClose(o);
            else o = F;

            h.o = (o) ? o.addClass(c.overlayClass).prependTo('body') : F;
            if (ie6) { $('html,body').css({ height: '100%', width: '100%' }); if (o) { o = o.css({ position: 'absolute' })[0]; for (var y in { Top: 1, Left: 1 }) o.style.setExpression(y.toLowerCase(), "(_=(document.documentElement.scroll" + y + " || document.body.scroll" + y + "))+'px'"); } }

            if (c.ajax) {
                var r = c.target || h.w, u = c.ajax, r = (typeof r == 'string') ? $(r, h.w) : $(r), u = (u.substr(0, 1) == '@') ? $(t).attr(u.substring(1)) : u;
                r.html(c.ajaxText).load(u, function () { if (c.onLoad) c.onLoad.call(this, h); if (cc) h.w.jqmAddClose($(cc, h.w)); e(h); });
            }
            else if (cc) h.w.jqmAddClose($(cc, h.w));

            if (c.toTop && h.o) h.w.before('<span id="jqmP' + h.w[0]._jqm + '"></span>').insertAfter(h.o);
            (c.onShow) ? c.onShow(h) : h.w.show(); e(h); return F;
        },
        close: function (s) {
            var h = H[s]; if (!h.a) return F; h.a = F;
            if (A[0]) { A.pop(); if (!A[0]) L('unbind'); }
            if (h.c.toTop && h.o) $('#jqmP' + h.w[0]._jqm).after(h.w).remove();
            if (h.c.onHide) h.c.onHide(h); else { h.w.hide(); if (h.o) h.o.remove(); } return F;
        },
        params: {}
    };
    var s = 0, H = $.jqm.hash, A = [], ie6 = $.browser.msie && ($.browser.version == "6.0"), F = false,
i = $('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({ opacity: 0 }),
e = function (h) { if (ie6) if (h.o) h.o.html('<p style="width:100%;height:100%"/>').prepend(i); else if (!$('iframe.jqm', h.w)[0]) h.w.prepend(i); f(h); },
f = function (h) { try { $(':input:visible', h.w)[0].focus(); } catch (_) { } },
L = function (t) { $()[t]("keypress", m)[t]("keydown", m)[t]("mousedown", m); },
m = function (e) { var h = H[A[A.length - 1]], r = (!$(e.target).parents('.jqmID' + h.s)[0]); if (r) f(h); return !r; },
hs = function (w, t, c) {
    return w.each(function () {
        var s = this._jqm; $(t).each(function () {
            if (!this[c]) { this[c] = []; $(this).click(function () { for (var i in { jqmShow: 1, jqmHide: 1 }) for (var s in this[i]) if (H[this[i][s]]) H[this[i][s]].w[i](this); return F; }); } this[c].push(s);
        });
    });
};
})(jQuery);

function MultipleFieldsValidatorEvaluateIsValid(val) {
    controltovalidateIDs = val.controlstovalidate.split(',');
    switch (val.condition) {
        case 'OR':
            for (var controltovalidateIDIndex in controltovalidateIDs) {
                var controlID = controltovalidateIDs[controltovalidateIDIndex];
                if (ValidatorTrim(ValidatorGetValue(controlID)) != '') {
                    return true;
                }
            }
            return false;
            break;
        case 'XOR':
            for (var controltovalidateIDIndex in controltovalidateIDs) {
                var controlID = controltovalidateIDs[controltovalidateIDIndex];
                if (controltovalidateIDIndex == '0') {
                    var previousResult = !(ValidatorTrim(ValidatorGetValue(controlID)) == '');
                    continue;
                }
                var currentResult = !(ValidatorTrim(ValidatorGetValue(controlID)) == '');
                if (currentResult != previousResult) {
                    return true;
                }
                previousResult != currentResult;
            }
            return false;
            break;
        case 'AND':
            for (var controltovalidateIDIndex in controltovalidateIDs) {
                var controlID = controltovalidateIDs[controltovalidateIDIndex];
                if (ValidatorTrim(ValidatorGetValue(controlID)) == '') {
                    return false;
                }
            }
            return true;
            break;
    }
    return false;
}
/*** END ***/




