var gdmcms = new function() {
    this.cookiePrefix = "";
    this.setup= function(){
        this.setStyles();
        this.setNotify();
        this.setDialog();
    }
    
    this.setStyles = function(){
        $(document).ready(function() {
            $( "input:submit:not(.notui), input:button:not(.notui),input:checkbox:not(.gridtf,.notui,.icon), .button:not(.notui), .table-button" ).button();
            gdmcms.setupInFieldLabel();
            inputs = $("input:not(.notui) , select:not(.notui) ,textarea:not(.notui)");
            $( "input:checkbox.icon" ).checkIcon();
            $(".dialogueLink").click(function(event){
                event.preventDefault();
                url = $(this).attr("href");
                title = $(this).html();
                gdmcms.openDialog(url, {
                    title:title, 
                    fragment: ".page_content"
                })
            });
            
            $.each(inputs,function(){
                element =  $(this);
                if (!element.hasClass('ui-state-default')) {
                    $(this).addClass('ui-state-default');
                    $(this).bind({
                        focusin: function() {
                            $(this).toggleClass('ui-state-focus');
                        },
                        focusout: function() {
                            $(this).toggleClass('ui-state-focus');
                        }
                    });
                }
            });
           
            $( ".tabs" ).tabs({
                cookie: {
                    expires: 1
                }
            });
        
            if (($('.wysiwyg_basic').length + $('.wysiwyg').length) > 0){
                if(typeof initTinyMce == 'function') {
                    initTinyMce(CSS_FILE,SITE_PATH);
                }
            }
        });
    }
    
    this.setupInFieldLabel = function(){
        $('.inFieldLabel').each(function(){
            label = $(this);
            labelParent = label.parent();
            if (!labelParent.hasClass('inFieldLabelsWrap')) {
                label.parent().wrapInner("<div class='inFieldLabelsWrap'></div>");
                label.inFieldLabels();
            }
        })
    }
    this.setNotify = function(){
        $("#messageContainer").notify();
    }
    this.setDialog = function(){
        
        $( "#overlay" ).dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            hide: 'Fade',
            dialogClass: 'shadow',
            beforeClose: function(event, ui) {
                if (gdmcms.hasWysiwyg()){
                    unloadWysiwyg( $(this));
                }
            }
        });
        
        $( "#confirmWrap" ).dialog({
            autoOpen: false,
            resizable: false,
            modal: true,
            hide: 'Fade',
            dialogClass: 'shadow'
        });
    }
    
    this.hasWysiwyg = function(){
        return ( (typeof hasWysiwyg == 'function') && (hasWysiwyg()) );
    }
    
    this.htmlentities =  function(str) {
        return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
    }
    this.nl2br =   function (text){
        text = escape(text);
        re_nlchar ="";
        if(text.indexOf('%0D%0A') > -1){
            re_nlchar = /%0D%0A/g ;
        }else if(text.indexOf('%0A') > -1){
            re_nlchar = /%0A/g ;
        }else if(text.indexOf('%0D') > -1){
            re_nlchar = /%0D/g ;
        }
        return unescape( text.replace(re_nlchar,'<br />') );
    }
    
    this.showMsgBox = function (title, mesg, type, expireTime) {
        if ( MSG_ERROR == type ){
            expireTime = (expireTime == null) ? false : expireTime;
        }else{
            expireTime = (expireTime == null) ? 5000 : expireTime;
        }
          
        $("#messageContainer").notify({
            custom:true
        }).notify("create", {
            title: title,
            text: mesg          
        },{
            expires: expireTime,
            beforeopen: function(){
                classes = gdmcms.getMesgClasses(type);
                $(this).removeClass().addClass('ui-corner-all '+classes.state);
                $(this).find("#messageIcon").removeClass().addClass('ui-icon ui-notify-icon '+classes.icon);
            }
        });
  
    }
    
    this.getMesgClasses = function(type){
        switch (type) {
            case MSG_INFO:
                stateClass = "ui-state-highlight";
                iconClass = " ui-icon-info";
                break;
            case MSG_OK:
                stateClass = "ui-state-highlight";
                iconClass = "ui-icon-check";
                break;
            case MSG_WARN:
                stateClass = "ui-state-highlight";
                iconClass = "ui-icon-alert";
                break;
            case MSG_ERROR:
                stateClass = "ui-state-error";
                iconClass = "ui-icon-alert";
                break;
            default:
                stateClass = "ui-state-highlight";
                iconClass = "ui-icon-info";
                //                console.log("getMesgClasses(): Unknown message type "+type);
                
                break;              
        }
        result = {
            icon: iconClass, 
            state: stateClass
        };
        return result;
    }
    this.checkMail =function(){
        gdmcms.showMsgBox("Mail", "Checking for new mail . . .", MSG_INFO)
        $.post('/plugins/mailclient/checkmail.php',{
            callback:'true'
        } ,function(data){          
            data =  gdmcms.parseJSON(data);
            gdmcms.showMsgBox("Mail", data.mesg, MSG_INFO, false);
            emailGrid = $('#emailGrid');
            if (emailGrid){
                emailGrid.trigger("reloadGrid");
            }
        });
    }
    
    this.updateMsgBox = function(text, type, id, callback) {
        id = (id == null)? "mesg" : id;
        stateClass = "ui-state-highlight";
        iconClass = "ui-icon-alert";
        callback =  (callback == null)? function(){}: callback;
        
        //TODO Create proper OK and WARN css classes
        switch (type) {
            case MSG_INFO:
                stateClass = "ui-state-highlight";
                iconClass = " ui-icon-info";
                break;
            case MSG_OK:
                stateClass = "ui-state-highlight";
                iconClass = "ui-icon-check";
                break;
            case MSG_WARN:
                stateClass = "ui-state-highlight";
                iconClass = "ui-icon-info";
                break;
            case MSG_ERROR:
                stateClass = "ui-state-error";
                iconClass = "ui-icon-alert";
                break;
        }        
        $("#"+id).fadeTo(200,'0.1',function(){
            $("#"+id+" #msgIcon").removeClass().addClass('ui-icon '+iconClass);
            $("#"+id+" #msginner").removeClass().addClass('ui-corner-all '+stateClass);
            $("#"+id+" #msgtxt").html(text);
            $("#"+id).fadeTo(900,1,
                function()
                {
                    callback.call();
                    
                });
        });
    }
    
    this.login = function(startPage)
    {
        gdmcms.updateMsgBox('Validating....', MSG_INFO, "loginMsg");
        loginForm = $("#login_form");
        //remove all the class add the messagebox classes and start fading
                                 
        //check the username exists or not from ajax
        $.post(  
            gdmcms.addCallback(loginForm.attr("action")),  
            loginForm.serialize(),  
            function(data){
                data =  gdmcms.parseJSON(data);
                callback=function(){};
                if(data.type==MSG_OK) //if correct login detail
                {
                    callback = function(){
                        document.location=startPage;
                    };
                }
                gdmcms.updateMsgBox(data.mesg, data.type, "loginMsg",callback);
            });  
        
        return false;//not to post the  form physically
    }
    
    this.addCallback = function(url){
        if (url != undefined){
            url += (url.indexOf("?") != -1) ? "&" :"?";
        }
        url += "callback=true";
        return url;
    }
    this.addFromInline = function(url){
        url += (url.indexOf("?") != -1) ? "&" :"?";
        url += "inline=true";
        return url;
    }
    this.closeDialog =function(effect){
    
        $( "#overlay .content" ).children().remove();
        if (effect != undefined){
            var oldeffect =  $( "#overlay" ).dialog( "option", "hide" );
            $( "#overlay" ).dialog( "option", "hide", effect );
            $( "#overlay" ).dialog("close");
            $( "#overlay" ).dialog( "option", "hide", oldeffect );
        }else{
            $( "#overlay" ).dialog("close");
        }
        
        $( "#overlay .content" ).css("height", "");
        $( "#overlay .content" ).css("width", "");
        
    };
     
    this.openDialog = function(content, options,callback){
        callback =  (callback == null)? function(){}: callback;
        $( "#overlay" ).dialog( "option", {
            buttons: null
        });
        isURL = true;
        if (options != null && options.isURL != undefined){
            isURL = options.isURL ;
        }
        if (isURL){
            content =this.addCallback(content);
        }
        this.closeDialog();
        defaultWidth = 312;
        defaultHeight = 223;
        currentWidth = $( "#overlay" ).width();
        currentHeight = $( "#overlay" ).height();
        newWidth =  (currentWidth >defaultWidth) ? currentWidth : defaultWidth;
        newHeight=  (currentHeight >defaultHeight) ? currentHeight : defaultHeight;
        $( "#overlay" ).dialog( "option", "width", newWidth);
        $( "#overlay" ).dialog( "option", "height", newHeight);
        $( "#overlay" ).dialog( "option", "title", options.title );
        
        if (isURL){
            $( "#overlay .content" ).html('<div id="dialogue" class="ui-jqgrid loadingWrap" style="display: block"><div class="loading ui-state-default ui-state-active" style="display: block">Loading...</div></div>');
            if ( options.fragment != undefined){
                content = content +" "+options.fragment ;
            }
            //            console.log("Load "+content);
            $( "#overlay .content" ).load(content,function(response, status, xhr) {
                gdmcms.setupDilogue(options, callback);
                gdmcms.setStyles();
            });
        }else{
            $( "#overlay .content" ).html(''+content+'');
            gdmcms.setupDilogue(options, callback);
            gdmcms.setStyles();
        }
        return false;
    }
    this.setupDilogue = function(options,callback){
        callback =  (callback == null)? function(){}: callback;
        var firstChild = $( "#overlay .content" ).find(':first-child');
        var secondChild = firstChild.find(':first-child');
        var firstWidth = firstChild.width();
        var secondWidth = secondChild.width();
        var newWidth = (firstWidth> secondWidth) ? firstWidth :secondWidth;
        if (newWidth != null){
            $( "#overlay" ).width(newWidth);
        }
        cancelButton = $( "#overlay .content" ).find('#cancel');
        if (cancelButton.length > 0){
            cancelButton.attr("onclick","");
            cancelButton.click(function(){
                gdmcms.closeDialog();
                return false;
            });
        }
        okButton = $( "#overlay .content" ).find('#ok');
        if (okButton.length > 0){
            okButton.attr("onclick","");
            okButton.click(function(){
                gdmcms.closeDialog();
                return true;
            });
        }
        $( "#overlay" ).dialog( "option", "width", "auto" );
        $( "#overlay" ).dialog( "option", "height", "auto");
        $( "#overlay" ).dialog( "option", options);
        $( "#overlay" ).dialog('open');
        $( "#overlay" ).dialog('option', 'width', $( "#overlay" ).parent().width()); 
        callback.call();
        gdmcms.centerDialogue();
    }
    this.centerDialogue = function(){
        $( "#overlay" ).parent().position({
            of: window,
            my: "center",
            at: "center",
            using: function(to) {
                $(this).animate(to);
            }
        });
    }
    this.editRow = function(url, options, element)
    {
        var callingGrid = element.parents().find('.ui-jqgrid-btable');
        callback = function(){
            formElement = $("#overlay").find("form");
          
            var options = { 
                dataType:  'json', 
                url: gdmcms.addCallback(formElement.attr("action")),
                success:   function(data, statusText, xhr, $form){
                    title=  "Save";
                    if (data.title  != undefined ){
                        title = data.title;
                    }else if   (options != null && options.title != undefined){
                        title = options.title;
                    }
               
                    gdmcms.showMsgBox(title,data.mesg, data.type);
                    if ( data.type == MSG_OK ){
                        gdmcms.closeDialog();
                        callingGrid.trigger("reloadGrid");
                    }
                }
            }; 
            formElement.ajaxForm(options); 
        };
        this.openDialog(url, options, callback);
        return false;
    } 
    this.getResponse =    function(data, statusText, xhr, $form){
        //(title, mesg, type, expireTime) 
        gdmcms.showMsgBox("Upload",data.mesg, data.type);
        if ( data.type == MSG_OK ){
            gdmcms.closeDialog();
            callingGrid.trigger("reloadGrid");
        }
    }
  
    this.saveRow = function(rowId, url, element)
    {
        url = this.addCallback(url);
        url = this.addFromInline(url);
        var callingGrid = element.parents().find('.ui-jqgrid-btable');
        callingGrid.jqGrid('setGridParam',{
            'editurl':url
        });
        callingGrid.jqGrid('saveRow',rowId, function(data){
            return gdmcms.inlineUpdated(data);
        });

        return false;
    } 
    this.restoreRow = function(element)
    {
        var callingGrid = element.parents().find('.ui-jqgrid-btable');
        callingGrid.restoreRow(lastsel);
    }

    this.deleteRow = function(url,options,element)
    {
        var callingGrid = element;
        this.confirm("Delete row?","Confirm",function(){
            url =gdmcms.addCallback(url);
            $.get(url, function(data) {
                data =  gdmcms.parseJSON(data);
                gdmcms.showMsgBox("Delete row",data.mesg,data.type);
                if (data.type != MSG_ERROR){
                    callingGrid.trigger("reloadGrid");
      
                }
            });
        }, function(){
            //
            })
        return false;
    }
    
    this.inlineUpdated = function(data){
        data = gdmcms.parseJSON(data.responseText );
        showButtons(data.extra);
        return true;
    }
  
    this.newRow = function(url, options, element)
    {
        var callingGrid = element.parents().find('.ui-jqgrid-btable');
        callback = function(){
            formElement = $("#overlay").find("form");
     
            if (formElement.length > 0){
                var options = { 
                    dataType:  'json', 
                    //                    beforeSubmit:  function(){
                    //                        gdmcms.showMsgBox("Upload","Uploading . . .", MSG_INFO);
                    //                    },
                    url: gdmcms.addCallback(formElement.attr("action")),
                    success:   function(data, statusText, xhr, $form){
                        title=  "Save";
                        if (data.title  != undefined ){
                            title = data.title;
                        }else if   (options != null && options.title != undefined){
                            title = options.title;
                        }
                        gdmcms.showMsgBox(title,data.mesg, data.type);
                        if ( data.type == MSG_OK ){
                            gdmcms.closeDialog();
                            callingGrid.trigger("reloadGrid");
                        }
                    }
                }; 
                formElement.ajaxForm(options); 
            }
        };
        
        return this.openDialog(url, options, callback);
    } 
    this.writeEmail = function(url, options)
    {
        defaultOptions = {
            preMessage: "Sending . . .",
            preTitle: "Mail"
        };
        options = $.extend(defaultOptions, options);

        callback = function(){
            $("#sendForm").submit(function(){  
                action = $('#action').attr('value');
                if (action == "save"){
                    options.preMessage = "Saving . . .";
                }
                gdmcms.showMsgBox(options.preTitle,options.preMessage, MSG_INFO);
                $.post(  
                    gdmcms.addCallback($("#sendForm").attr("action")),  
                    $("#sendForm").serialize(),  
                    function(data){
                        data =gdmcms.parseJSON(data);
                        gdmcms.showMsgBox(data.title,data.mesg,data.type);
                        if ( data.type == MSG_OK ){
                            gdmcms.closeDialog();
                        }   
                    }  
                    );  
                return false;  
            });  
        };
        return this.openDialog(url, options,callback);
    } 
    this.showemail =function (id){
        $('#emailBody').html("<br>Loading message....");
        $.post("/plugins/mailclient/fetchEmail.php?id="+id,{
            callback:'true'
        } ,function(data){
            data =gdmcms.parseJSON(data);
            $('#emailMessage .title').html(data.subject);
            $('#emailMessage .content').html(data.mesg);
            $('.attachmentButton').hover(
                function(){ 
                    $(this).addClass("ui-state-hover"); 
                },
                function(){ 
                    $(this).removeClass("ui-state-hover"); 
                }
                )
        });
        return false;
    }
    this.popUpEmail =function (id){
        url="/plugins/mailclient/fetchEmail.php?id="+id;
        url=gdmcms.addCallback(url);
        $.get(url, function(data) {
            data =gdmcms.parseJSON(data);
            $( "#overlay .content" ).css("height", "600px");
            $( "#overlay .content" ).css("width", "618px");
            $( "#overlay .content" ).html(data.mesg);
            gdmcms.setupDilogue({
                title: data.subject
            });
        });
        return false;
    }
    this.idToRef = function(id){
        var str = '' + id;
        while (str.length < 4) {
            str = '0' + str;
        }   
        str = 'RD' +  str;
        return str;
    }
    
    this.replaceRef = function(str, replacement){
        return str.replace(/RD([0-9]+)/,replacement)
    }
    
    this.composeMail = function (){
        gdmcms.writeEmail("/plugins/mailclient/write.php",{
            title: "Write email"
        });
    }
    this.confirm = function(mesg, tile,trueFunction, falseFunction)
    {
        if (trueFunction == undefined ) trueFunction = function(){};
        if (falseFunction == undefined ) falseFunction = function(){};
        
        
        $( "#confirmWrap" ).dialog( "option",  {
            title: tile,
            buttons: {
                "Yes": function() {
                    trueFunction.call();
                    $( this ).dialog( "close" );
                },
                "Cancel": function() {
                    falseFunction.call();
                    $( this ).dialog( "close" );
                }
            }
        });
        $( "#confirmWrap .content" ).html(''+mesg+'');
        $( "#confirmWrap" ).dialog('open');
        gdmcms.setStyles();
        return false;
      
    }
    this.okDilogue = function(mesg, tile,onOkFunction)
    {
        if (onOkFunction == undefined ) onOkFunction = function(){};
        return this.openDialog("<form action=''>"+mesg+"</form>", {
            isURL: false,
            title: tile,
            buttons: {
                "OK": function() {
                    onOkFunction.call();
                    $( this ).dialog( "close" );
                }
            }
        });
    }
    this.setupLeftMenu =  function (element){
        $(document).ready(function() {
            element.click(function () {
                return  gdmcms.navClicked($(this));
            });
        });
    };
    this.navClicked = function (element){
        childMenu=element.parent().children('ul');
        if(childMenu.is(":visible")){
            gdmcms.closeMenu(childMenu);
        }else{
            $('.parentMenu').children('ul').slideUp('fast');
            gdmcms.openMenu(childMenu);
        }
        return false;
    }
    this.openMenu = function (element){
        element.slideDown('fast');            
        $.cookie(gdmcms.cookiePrefix + '_openMenu', element.attr('id'));
    } 
    this.closeMenu = function (element){
        element.slideUp('fast');
        $.cookie(gdmcms.cookiePrefix + '_openMenu', null);
    } 
    this.openMenuByCookie = function (){
        childId=  $.cookie(gdmcms.cookiePrefix + '_openMenu');
        if (childId != null){
            $('#'+childId).show('fast'); 
        }
    } 
    this.isJson =function (data){
        isJson = true
        try
        {
            jsonData = jQuery.parseJSON( data );
        }
        catch(e)
        {
            isJson = false;
        } 
        return isJson;
    }
    this.parseJSON = function(data){
        if(data == null){
            data = {
                mesg:"Response empty",
                type: MSG_ERROR
            };
        }else if (typeof data=="string"){
            try
            {
                data = jQuery.parseJSON( data );
            }
            catch(e)
            {
                data = {
                    mesg:"Parse error on response "+data,
                    type: MSG_ERROR
                };
            } 
    
        } else if (typeof data!="object"){
            //            console.log("parseJSON(): Unknown type passed = "+typeof data);
            data = {
                mesg:"Parse error on response:  Unknown type passed = "+typeof data,
                type: MSG_ERROR
            };
        }
        return data;
    }
    this.editApplication = function(url){
        callback = function(){
            $("#sendForm").submit(function(){  
                
                //                gdmcms.showMsgBox("Saving", MSG_INFO,'chkMesgDiv');
                //                $.post(  
                //                    gdmcms.addCallback($("#sendForm").attr("action")),  
                //                    $("#sendForm").serialize(),  
                //                    function(data){
                //                        gdmcms.showMsgBox(data.mesg, data.type,'chkMesgDiv');
                //                        if ( data.type == MSG_OK ){
                //                            gdmcms.closeDialog();
                //                        }   
                //                    }  
                //                    );  
            
                return false;  
            });  
    
        };
        return this.openDialog(url, {
            title: "Edit Candidate"
        },callback);
    }
    this.addJSFile = function(url){   
        $('head').append('<script type="text/javascript" src="'+url+'"></script>');
    }
    this.addCSSFile = function(url){     
        $('head').append('<link rel="stylesheet" href="'+url+'" type="text/css" />');
    }
    this.log = function(msg){
        if (!(typeof console == "undefined")){
            if (!(typeof console.log == "undefined")){
                console.log(msg);
            }
        }
    }
}

String.prototype.startsWith = function(str){
    return (this.indexOf(str) === 0);
}

var MSG_INFO =1;
var MSG_OK = 2;
var MSG_WARN = 3; 
var MSG_ERROR = 4;
$(document).ready(function() {
    gdmcms.setup();
});
