//=====================================================//
var Validate = {
    //=====================================================//
    validateFormData: function(json, statusText, jqFormObj, extraParamObj){
        if (typeof(json) == 'string') {
            eval('var json =' + json);
        }

        var callbackFunction = null;
        var callbackFunctionOnError = null;
        if (extraParamObj) {
            if (extraParamObj.callback) {
                callbackFunction = extraParamObj.callback;
            }

            if (extraParamObj.callbackOnError) {
                callbackFunctionOnError = extraParamObj.callbackOnError;
            }
        }

        $(jqFormObj).find('.progressSpan').removeClass('progress').css('display', 'none');
        $(jqFormObj).find('div').removeClass('error');
        $(jqFormObj).find('div strong[class=message]').remove();
        
        var errorCount = json.errorCount;
        if(errorCount == 0){
            $(jqFormObj).find("#errorDisplayBox").css('display', 'none');
            
            var successHandler = jqFormObj.attr("success");
            if (successHandler) {
                eval(successHandler);
            }
            
            var successMsgFld = $('input[name=successMsg]', jqFormObj);
            var dialogMsgFld  = $('input[name=dialogMessage]', jqFormObj);
            
            if ($(successMsgFld).length > 0){
                var formHt = $(jqFormObj).height();
                //$(jqFormObj).css('height', formHt + 'px'); 
                $(jqFormObj).hide();
                $(jqFormObj).html($(successMsgFld).val());
                $(jqFormObj).slideDown(2000);
            } else if ($(dialogMsgFld).length > 0){
                Util.alert($(dialogMsgFld).val());
            } else if (returnUrl) {
                document.location = returnUrl;
            } else {
                returnUrl = json.returnUrl;
                if (returnUrl) {
                    document.location = returnUrl;
                } else {
                    var returnUrl = $(jqFormObj).find('#retUrl').val();
                    if (returnUrl) {
                        document.location = returnUrl;
                    } else if(callbackFunction) {
                        callbackFunction.call(this, json, statusText, jqFormObj, extraParamObj);
                    }
                }

            }
        } else {

            var htmlText  = "";
            htmlText += "<h4>The following errors occured</h4>";

            $(jqFormObj).find('div').removeClass('error');
            $(jqFormObj).find('div strong[class=message]').remove();

            $.each(json.errors, function() {
                fieldName = this.name;
                var fieldObj = $('#fld_' + fieldName, jqFormObj);

                var parent = "";

                if (fieldObj.length > 0){
                    parent = fieldObj.parent('div');
                } else if (fieldObj.attr('type') == 'radio') {
                    // since each radio is encapsulated in each div we would simply
                    // add the error class to the parent - two level up
                    parent = fieldObj.parent('div').parent('div');

                } else {
                    /*** radio ***/
                    fieldObj = $('#' + fieldName + '_1',  jqFormObj);
                    if (fieldObj.length > 0){
                        var wrapper = $(fieldObj).closest('.form-row-wrapper');
                        if (wrapper.length > 0){
                            parent = wrapper;
                        } else {
                            parent = fieldObj.parent('div').parent('div');
                        }
                    }
                }
                if(parent != ""){
                    parent.addClass('error');
                }

                if (this.msg) {
                    htmlText  += '<p>' + this.msg + '</p>';
                    if(parent != ''){
                        parent.prepend("<strong class='message'>" + this.msg + "</strong>");
                    }
                    
                    if ($(jqFormObj).hasClass('columnar')){
                        
                        if(fieldObj.attr('type') == 'checkbox'){
                            lblWidth = fieldObj.css('margin-left');
                        } else {
                            lblWidth = $('label', parent).outerWidth(true) + 'px';
                        }

                        $('strong[class=message]', parent).css('margin-left', lblWidth);
                    }
                }

                $("#label_" + fieldName).addClass("formFieldLabelError");
            });
            
            /*
            $(jqFormObj).find("#errorDisplayBox").html(htmlText);
            $(jqFormObj).find("#errorDisplayBox").addClass('errorDisplayBox');
            $(jqFormObj).find("#errorDisplayBox").css('display', 'block');
            */

            if(callbackFunctionOnError) {
                callbackFunctionOnError.call(this, json, statusText, jqFormObj, extraParamObj);
                return;
            }

            var customErrorField = $('.customErrorBox', jqFormObj);
            if ($(customErrorField).length > 0){
                $(jqFormObj).find(".customErrorBox").css('display', 'block');
            }
        
            if ($('#captcha').length > 0){
                $('a.reloadCaptcha').click();
            }
        }
    }
}

//------------------------------------------------//
var Lang = {
    get: function(key) {
        return Lang.data[key];
    }
}

//------------------------------------------------//
var Util = {
    alertWindowWidth: 350,
    alertWindowHeight: 200,
    
    changeLangDropdown: function(url, hasSEO){
        var lang = document.getElementById('lang').value;
        var link = '';
        if (hasSEO == 1){
            link = '/' + lang + '/' + url;
        } else {
            link = url + '&lang=' + lang;
        }
        document.location = link;
    },

    //=====================================================//
    getCDATAValue: function(text){
        //*** actual text: &lt;![CDATA[Chinese]]&gt;
        //*** actual text: <![CDATA[Chinese]]>;
        //*** actual text: <!--[CDATA[<p class="error">userNameError</p>]]-->

        if (!text) return;

        if (text.substr(0, 1) == "&") {
            text = text.substr(12);
            text = text.substr(0,text.length-6);
        }
        else if (text.substr(0, 4) == "<!--") {
            text = text.substr(11);
            text = text.substr(0,text.length-5);
        }
        else {
            text = text.substr(9);
            text = text.substr(0,text.length-3);
        }
        return text;
    },

    //=====================================================//
    getLoginStatus: function(handler){

        /*------------- CHECK THE LOGIN STATUS -------------*/
        var url = "/index.php?_room=member&_spAction=loginStatus&showHTML=0";
        $.get(url, {}, function (data) {
            /*------------- Show message if not logged in -------------*/
            if (!data.loggedIn){
                var msg = data.msg + ''; //*** convert to string from xml
                $.unblockUI();
                $.blockUI({ message: msg, css: { width: '275px' } })

                /*------------- if yes go to login page -------------*/
                $('#login_yes').click(function() {
                    $.blockUI({ message: "<h1>Please wait...</h1>" });
                    
                    /*------------- SET THE CURRENT URL IN SESSION VAR -------------*/
                    var url = "/index.php?_spAction=currentUrlInSession&showHTML=0";
                    $.get(url, {currentUrl:document.location.href}, function (data) {
                        document.location = data.loginUrl;
                    }, 'json');
                });
                
                /*------------- if no just return -------------*/
                $('#login_no').click(function() {
                    $.unblockUI();
                    return false;
                });
                return false;
            } else {
                handler.call();
            }

        }, 'json');
        
    },

    showLoading: function(){
        $.blockUI({ message: "<h4>Loading... Please wait...</h4>" });
    },

    getScrollForUIDialog: function(text, options) {
        var height = options.height;
        height -= 100;
        var selectedSet = $('<div>')
                          .append($('<div>' + text + '</div>')
                                  .css({'overflow-y': 'auto', 'width': '94%', 'height': height + 'px'})
                           );
        return selectedSet;
    },

    initDialog: function() {
        //just to make sure we are not dealing with the unintended (old used) div for the dialog
        $("div.popcontents").parents('.ui-dialog:hidden').remove();
        $("div.popcontents").remove();
        
        var dialogCount = $('div.popcontents').length;
        var text = 'dialog';
        if (dialogCount == 0) {
            text = 'dialog';
        } else {
            text = 'dialog' + dialogCount;
        }
        
        $('body').append("<div id='" + text + "' class='popcontents'><div>");
        
        //returnd dialog div id
        return '#' + text;
    },

    initDialog2: function() {
        var dialogCount = $('div.popcontents').length;
        var text = 'dialog';
        if (dialogCount == 0) {
            text = 'dialog';
        } else {
            text = 'dialog' + dialogCount;
        }
        
        $('body').append("<div id='" + text + "' class='popcontents'><div>");
        
        //returnd dialog div id
        return '#' + text;
    },

    dialogDefaults: {bgiframe: true,
                     modal: true,
                     overlay: {opacity:0.8, background:'red'}
    },

    showProgress: function(message) {
        if (!message) {
            message = "Processing...";
        }
        $('#commonProgressMessage').remove();
        var text = "<div id='commonProgressMessage'>" + message + "<div>";
        text = $(text)
               .addClass('commonProgressMessage')
               .addClass('ui-corner-top');
        $.blockUI({ message: $(text).html() });
    },


    hideProgress: function() {
        $.unblockUI();
    },

    showProgressInd: function(message) {
        
        if ($('#progressInd').length > 0){
            return;
        }
        
        if (message == undefined) {
            message = 'Processing...';
        }
        var width = 100;
        var left = (screen.width-width)/2;
        var top = $(window).scrollTop();

        $('body')
        .append("<div id='progressInd' class='progressInd'><div></div></div>");
        $('#progressInd')
        .addClass('ui-corner-bl')
        .addClass('ui-corner-br');
        $('#progressInd')
        .css('left', left + 'px')
        .css('top', top + 'px');
        $('#progressInd div').html(message);
    },

    hideProgressInd: function() {
        $('#progressInd').remove();
        $('.progressInd').each(function(){
            $(this).remove();
        });
    },

    alert: function(text, callback, dialogTitle) {
        
        if (!dialogTitle){
            dialogTitle = '';
        }
        
        var dialogId = Util.initDialog2();
        $(dialogId).html(text);
        var xButtons = {};
        xButtons['OK'] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');
            
            if (callback) {
                callback.call();
            }
        };
        
        $(dialogId).dialog(
            $.extend(Util.dialogDefaults, {
                height: Util.alertWindowHeight,
                width: Util.alertWindowWidth,
                title: dialogTitle,
                buttons: xButtons,
                beforeclose: function(){}
            })
        );
    },

    showSimpleMessageInDialog: function(msg, options) {
        
        var id = Util.initDialog2();
        $(id).html(msg);
        
        var xButtons = {};
        
        xButtons[Lang.data.close] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');
        };
        
        var dialogTitle = '';
        
        var settings = $.extend({
             buttons: xButtons
            ,title: dialogTitle
        }, options);
        
        var x_dialog = $(id).dialog(
            $.extend(Util.dialogDefaults, settings)
        );
    },

    openDialogForLink: function(dialogTitle, w, h, showCloseBtn, extraParamObj) {
        if (!w){
           w = 450;
        }
        
        if (!h){
           h = 400;
        }

        var xButtons = {};
        
        if (!showCloseBtn) {
           showCloseBtn = false;
        }

        if (showCloseBtn){
	        xButtons[Lang.data.close] = function() {
	            $(this).dialog('close');
	            $(this).dialog('destroy');
	        };
        }

        if (!extraParamObj){
            extraParamObj = {};
        }

        if (extraParamObj.url) {
            url = extraParamObj.url;
        } else {
            url = $(this).attr('href');
            if (url == "" || url == "javascript:void(0)" || url == "javascript:void(0);"  || url == undefined ){
                url = $(this).attr('link');
            }
        }

        Util.showProgressInd();

        $.get(url, function(data){
            Util.initDialog();
            $('#dialog').html(data);

            var beforeCloseFunction = null;
            if (extraParamObj) {
                if (extraParamObj.beforeCloseFn) {
                    beforeCloseFunction = extraParamObj.beforeCloseFn;
                }
            }
            
            var x_dialog = $('#dialog').dialog(
                $.extend(Util.dialogDefaults, {
                    width: w,
                    height: h,
                    title: dialogTitle,
                	buttons: xButtons,
                	beforeclose:function(e, ui){
                        if(beforeCloseFunction) {
                            beforeCloseFunction.call();
                        }
                	}
                })
            );
            Util.hideProgressInd();
        });
    },

    showConfirmDialog: function(dialogTitle, msg, submitCallback, w, h){
        if (!w){
           w = 400;
        }
        
        if (!h){
           h = 100;
        }

        Util.showProgressInd();

        Util.initDialog();
        $('#dialog').html(msg);

        var xButtons = {};

        xButtons['OK'] = function() {
            submitCallback.call()
            $(this).dialog('close');
            $(this).dialog('destroy');
        };

        xButtons['Cancel'] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');
            $('#dialog').remove();
        };

        var x_dialog = $('#dialog').dialog(
            $.extend(Util.dialogDefaults, {
                title: dialogTitle,
                width: w,
                height: h,
                buttons: xButtons
            })
        );

        Util.hideProgressInd();
    },

    confirm: function(text, callback, options) {
        var settings = jQuery.extend({
             btn1Label: 'OK'
            ,btn2Label: 'Cancel'
        }, options);

        var dialogId = Util.initDialog();
        $(dialogId).html(text);

        var xButtons = {};
        xButtons[settings.btn1Label] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');

            if (callback) {
                callback.call(this, settings.btn1Label);
            }
        };
        xButtons[settings.btn2Label] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');

            if (callback) {
                callback.call(this, settings.btn2Label);
            }
        };

        $(dialogId).dialog(
            $.extend(Util.dialogDefaults, {
                height: 200,
                width: 350,
                buttons: xButtons
            })
        );
    },

    openFormInDialog: function(formName, dialogTitle, w, h, extraParamObj) {
        if (!w){
           w = 450;
        }
        if (!h){
           h = 400;
        }
        
        if (!extraParamObj){
            extraParamObj = {};
        }

        if (extraParamObj.url) {
            url = extraParamObj.url;
        } else {
            url = $(this).attr('href');
            if (url == "" || url == "javascript:void(0)" || url == "javascript:void(0);"  || url == undefined ){
                url = $(this).attr('link');
            }
        }
        Util.showProgressInd();

        $.get(url, function(data){
            Util.initDialog();
            $('#dialog').html(data);

            var beforeCloseFunction = null;
            if (extraParamObj) {
                if (extraParamObj.beforeCloseFn) {
                    beforeCloseFunction = extraParamObj.beforeCloseFn;
                }
            }

            var xButtons = {};

            xButtons['Submit'] = function() {
                $('#' + formName).submit();
            };

            xButtons['Cancel'] = function() {
                $(this).dialog('close');
                $(this).dialog('destroy');
                $('#dialog').remove();
            };

            var x_dialog = $('#dialog').dialog(
                $.extend(Util.dialogDefaults, {
                    width: w,
                    height: h,
                    title: dialogTitle,
                    buttons: xButtons,
                	beforeclose:function(e, ui){
                        if(beforeCloseFunction) {
                            beforeCloseFunction.call();
                        }
                	}
                })
            );

            if (extraParamObj.validate) {
                var extraParValid = {};
                if (extraParamObj.callbackOnSuccess) {
                    extraParValid.callback = extraParamObj.callbackOnSuccess;
                }
    
                var options = {
                    success: function(json, statusText, jqFormObj) {
                        Validate.validateFormData(json, statusText, jqFormObj, extraParValid);
                        Util.hideProgressInd();
                    },
                    beforeSubmit: function(frmData) {
                        Util.showProgressInd();
                    },
                    dataType: 'json'
                };
    
                $('#' + formName).ajaxForm(options);
            }

            Util.hideProgressInd();
        });
    },
    
    setUpAjaxFormGeneral: function(formName, cbFunction, beforeSubmitFn) {
        $('#' + formName).livequery(function() {

            /****************************************************/
            var extraPar = {};

            if (cbFunction) {
                extraPar.callback = cbFunction;
            }

            var options = {
                success: function(json, statusText, jqFormObj) {
                    Validate.validateFormData(json, statusText, jqFormObj, extraPar);
                    Util.hideProgressInd();
                },
                beforeSubmit: function(frmData) {
                    if (beforeSubmitFn) {
                        beforeSubmitFn.call(this, frmData);
                        extraPar.callback = cbFunction;
                    }
                    Util.showProgressInd();
                },
                dataType: 'json'
            };

            $('#' + formName).ajaxForm(options);

        });
    },

    prepopulatedTextbox: function() {
        $("input:text[rel^='pptxt'],textarea[rel^='pptxt']")
        .livequery(function() {
            e = $("input:text[rel^='pptxt'],textarea[rel^='pptxt']");

            for (i=0;i<$(e).length;i++) {
                if ($(e[i]).val()=='') {
                    t = $(e[i]).attr('rel');
                    t = t.split("pptxt:");
                    $(e[i]).css('color','#999');
                    $(e[i]).val(t[1]);
                }
            }

            $(e).focus(function() {
                t = $(this).attr('rel');
                t = t.split("pptxt:");
                var value    = $(this).val().replace(/[\r\n]/g, '');
                var pptxtval = t[1].replace(/[\r\n]/g, '');
                if (value == pptxtval) {
                    $(this).css('color','#444');
                    $(this).val('');
                }
            });
            $(e).blur(function() {
                t = $(this).attr('rel');
                t = t.split("pptxt:");
                if ($(this).val()=='') {
                    $(this).css('color','#999');
                    $(this).val(t[1]);
                }
            });
        });
    },

    clearPrepopulatedTextbox: function(container, frmData) {
        //frmData is an object containing form data

        var len = $("input:text[rel^='pptxt'],textarea[rel^='pptxt']", $(container)).length;
        $("input:text[rel^='pptxt'],textarea[rel^='pptxt']", $(container))
        .each(function(i) {
            var t = $(this).attr('rel');
            var fieldName = $(this).attr('name');
            t = t.split("pptxt:");
            var value    = $(this).val().replace(/[\r\n]/g, '');
            var pptxtval = t[1].replace(/[\r\n]/g, '');
            if (value == pptxtval) {
                $(this).val('');
                
                if ($.isArray(frmData)){
                    for (var i=0; i < frmData.length; i++) {
                        if (frmData[i].name == fieldName) {
                            frmData[i].value = '';
                        }
                    }
                }
            }
        });
    },

    setCKEditorValue: function(frmData, name){
        var fld_id  = "fld_" + name;
        editor_data = CKEDITOR.instances[fld_id].getData();
        $.each(frmData, function(){
            if(this.name == name){
                this.value = editor_data;
            }
        });
    },

    setJqFormFldValue: function(frmData, name, value){
        $.each(frmData, function(){
            if(this.name == name){
                this.value = value;
            }
        });
    },
    
    in_array: function(needle, haystack, argStrict) {
        // http://kevin.vanzonneveld.net
        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: vlado houba
        // +   input by: Billy
        // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
        // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
        // *     returns 1: true
        // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
        // *     returns 2: false
        // *     example 3: in_array(1, ['1', '2', '3']);
        // *     returns 3: true
        // *     example 3: in_array(1, ['1', '2', '3'], false);
        // *     returns 3: true
        // *     example 4: in_array(1, ['1', '2', '3'], true);
        // *     returns 4: false
    
        var key = '', strict = !!argStrict;
    
        if (strict) {
            for (key in haystack) {
                if (haystack[key] === needle) {
                    return true;
                }
            }
        } else {
            for (key in haystack) {
                if (haystack[key] == needle) {
                    return true;
                }
            }
        }
    
        return false;
    },
    
    isCountryUS: function(country){
        var arr1 = new Array('us'
                            ,'united states'
                            ,'united states of america'
                   );
        country = country.toLowerCase();
        if (Util.in_array(country, arr1)) {
            return true;
        } else {
            return false;
        }
    }

    ,getTranslation: function(e){
        e.preventDefault();
        var key = $(this).attr('key');
        var title = $(this).attr('dlgTitle');
        var width = $(this).attr('w');
        var height = $(this).attr('h');
        width = width ? width : 600;
        height = height ? height : 500;
        
        var url = '/index.php?_spAction=translation&key=' + key + '&showHTML=0';
        var params = {url: url};
        Util.openDialogForLink(title, width, height, false, params);
    },

    getCKEditorToolBarsFull: function(){
        toolbar =
        [
            ['Bold','Italic','Underline','Strike'],
            ['Cut','Copy','Paste','PasteText','PasteFromWord','-', 'SpellChecker', 'Scayt'],
            ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
            ['Source','-','Preview'],
            '/',
            ['NumberedList','BulletedList', 'Blockquote'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ['Link','Unlink','Anchor'],
            ['Image','Flash','Table','HorizontalRule','SpecialChar'],
            '/',
            ['Format','Font','FontSize'],
            ['TextColor'],
            ['Maximize']
        ];
        
        return toolbar;
    }
}

//------------------ SHOPPING BASKET --------------------//
var Basket = {
    miniCartTopOffset: 0,
    miniCartLeftOffset: 6,
    updatePromoCode: function(e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var data = '&promo_code=' + $('#promo_code').val();
        Util.showProgressInd('Updating...');
        $.getJSON(url, data, function(json) {
            Util.hideProgressInd();
            if(json.status == 'error') {
                alert(json.errorMsg);
            } else {
                alert(json.message);
                document.location = json.returnUrl;
            }
        });
    },

    showMiniCart: function(){
    	var leftOffset = Basket.miniCartLeftOffset;
    	var topOffset  = Basket.miniCartTopOffset;
        pos = $(this).offset();
        var liWidth = $(this).parent().width();
        var cartWidth = $('#miniCart').width();
    
        $('#miniCart')
        .css('left', pos.left - (cartWidth - liWidth) +leftOffset)
        .css('top', $('#main').offset().top + topOffset)
        .slideDown();
    },
    
    setupShippingForm: function() {
        var options = {
            success: function(json, statusText, jqFormObj) {
                Util.hideProgressInd();
                Validate.validateFormData(json, statusText, jqFormObj);
            },
            beforeSubmit: function() {
                Util.showProgressInd();
            },
            dataType: 'json'
        };
        $('#shippingForm').ajaxForm(options);

    },

    addToBasket: function(e) {
        e.preventDefault();
        var url = "/index.php?_room=basket&_spAction=addToBasket&room=&showHTML=0" ;
        var product_id = $(this).attr('product_id');
        var data = {'product_id': product_id}
        $.post(url, data, function (json) {
            if (json.status == 'error') {
                Util.alert(json.errorMsg);
                return;
            }
            //Util.alert(json.html);
            var count = parseInt(json.count) + 0; //convert to number
            var countText = count + ' ITEM';
            if (count > 1) {
                countText = count + ' ITEMS';
            }

            $("a span.shoppingBagCount").html("(" + countText + ")");

            //---------------------//
            $("#miniCart").html(json.miniCart);
            Basket.showMiniCart.call($('a.miniCartLink'));
            //------------------//
            setTimeout(function() {
                $('#miniCart').slideUp();
            }, 4000);
            
        }, 'json');
    },
    
    copyBillingToDeliveryAddress: function(e) {
        e.preventDefault();
        if ($('#fld_shipping_first_name').length > 0) {
            $('#fld_shipping_first_name').val($('#fld_cust_first_name').val());
            $('#fld_shipping_last_name').val($('#fld_cust_last_name').val());
            $('#fld_shipping_email').val($('#fld_cust_email').val());
            $('#fld_shipping_mobile').val($('#fld_cust_mobile').val());
        }
        $('#fld_shipping_address_flat').val($('#fld_cust_address_flat').val());
        $('#fld_shipping_address_street').val($('#fld_cust_address_street').val());
        $('#fld_shipping_address_town').val($('#fld_cust_address_town').val());
        $('#fld_shipping_address_state').val($('#fld_cust_address_state').val());
        $('#fld_shipping_address_country').val($('#fld_cust_address_country').val());
        $('#fld_shipping_address_po_code').val($('#fld_cust_address_po_code').val());
        $('#fld_shipping_address_country').change();
    }
}

$(function() {
    LoadReady.setupKeywordSearch();
    LoadReady.setupMiniCart();
});



