//=====================================================//
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');
        
        var errorCount = json.errorCount;
        if(errorCount == 0){
            $(jqFormObj).find("#errorDisplayBox").css('display', 'none');

            var successHandler = jqFormObj.attr("success");
            if (successHandler) {
                eval(successHandler);
            }

            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');

            $.each(json.errors, function() {
                fieldName = this.name;
                var fieldObj = $(jqFormObj).find('#fld_' + fieldName);

                var parent = fieldObj.parent('div');
                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');
                }
			    
                parent.addClass('error');
                if (this.msg) {
                    htmlText  += '<p>' + this.msg + '</p>';
                }

                $("#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 Lang = {
    get: function(key) {
        return Lang.data[key];
    }
}

//------------------------------------------------//
var Util = {
    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;

    },

    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();
        });
    },

    showSimpleMessageInDialog: function(msg) {

        Util.initDialog();
        $('#dialog').html(msg);
        
        var xButtons = {};
        
        xButtons[Lang.data.close] = function() {
            $(this).dialog('close');
            $(this).dialog('destroy');
        };
        
        var x_dialog = $('#dialog').dialog(
            $.extend(Util.dialogDefaults, {
                buttons: xButtons
            })
        );
    },

    openDialogForLink: function(dialogTitle, w, h) {
        if (!w){
           w = 450;
        }
        
        if (!h){
           h = 400;
        }

        url = $(this).attr('href');

        Util.showProgressInd();

        $.get(url, function(data){
            Util.initDialog();
            $('#dialog').html(data);

            var x_dialog = $('#dialog').dialog(
                $.extend(Util.dialogDefaults, {
                    width: w,
                    height: h,
                    title: dialogTitle
                })
            );
            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();

    },

    openFormInDialog: function(formName, dialogTitle, w, h) {
        
        if (!w){
           w = 450;
        }
        
        if (!h){
           h = 400;
        }

        url = $(this).attr('href');

        Util.showProgressInd();

        $.get(url, function(data){
            Util.initDialog();
            $('#dialog').html(data);

            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
                })
            );

            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;
            }
        });
    }
}
