// constants for message dispatching (same constants are defined in config.inc.php)
var ERROR   = 0;
var INFO    = 1;
var WARNING = 2;

 function formatMessage(jsonMsg, msgDivId){
   
    msgDivId = (msgDivId == null) ? '#message' : '#'+msgDivId;

    var level = jsonMsg.level;
    var message = jsonMsg.msg;

    jQuery(msgDivId).addClass('ui-widget');
    var msgDiv = '';

    if(level == ERROR){ //|| level == INFO || level == WARNING){
        msgDiv += '<div class="ui-state-error ui-corner-all"><p>';
        msgDiv += '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"/>';
        msgDiv += '<b>Alert: </b>'+message;
        msgDiv += '</p></div>';
    }else if(level == WARNING){
        msgDiv += '<div class="ui-state-warning ui-corner-all"><p>';
        msgDiv += '<span class="ui-icon ui-icon-notice" style="float: left; margin-right: 0.3em;"/>';
        msgDiv += '<b>Warning: </b>'+message;
        msgDiv += '</p></div>';
    }else if(level == INFO){
        msgDiv += '<div class="ui-state-highlight ui-corner-all"><p>';
        msgDiv += '<span class="ui-icon ui-icon-info" style="float: left; margin-right: 0.3em;"/>';
        msgDiv += '<b>Info: </b>'+message;
        msgDiv += '</p></div>';
    }
    //alert('sdfsdf'+msgDivId);
    jQuery(msgDivId).html(msgDiv);
}

function initAjaxForm(url, task, formId, gridId, dialogId){
    dialogId = (dialogId == null) ? 'dialog' : dialogId;

    $('#'+formId).ajaxForm({
        url:url,
        resetFrom:true,
        /*
         * if set to true multiple click on submit is processed as many time
         * DO NOT MAKE IT TRUE OR REMOVE IT AT ANY COST !!!!
         */
        async:false,
        success:function(status){
            closeDialog(dialogId);
            $('#'+gridId).trigger('reloadGrid');
            showMessage(status, task);
        }
    });
}

function closeDialog(dialogId){
    dialogId = (dialogId == null) ? '#dialog': '#'+dialogId;

    $(dialogId).empty();
    $(dialogId).dialog('close');
    $(dialogId).dialog('destroy');
}

function emptyDiv(divId){
    $('#'+divId).empty();
    $('#'+divId).fadeOut(500);
}

function showDialog(dialogId, url, successFunction){
    dialogId = (dialogId == null) ? '#dialog': '#'+dialogId;

    $(dialogId).dialog({
        modal:true,
        //width: 325,
        autoOpen:false,
        buttons:{
            'OK':function(){
                successFunction;
            },
            'Cancel': function(){
                $(dialogId).dialog('destroy');
            }
        },
        close:function(){
            $(dialogId).dialog('destroy');
        }        
    });

    $(dialogId).load(url, function(){
        // close any other previous message
        //$('#message').trigger('click');
        $(dialogId).dialog('open');
    });
}



/**
 * Blueprint for select/combo that requies chaining reload
 *
 * @param <string> src the id of the parent select/combo
 * @targer <string> the id of the child/target select/combo
 * @task <string> the task that is to be handled in the server side
 * @isLeaf <boolean> the value that specifies whether the parent needs to
 *                          trigger the reload of child
 * @child <Combo> the child Combo object
 * @name <string> [optional] the name that needs to be prepended
 */
function Combo(src, target, task, isLeaf, child, name){
    this.src = src;
    this.target = target;
    this.task = task;
    this.isLeaf = isLeaf;

    this.toString = function(){
        return name;
    }

    /**
     * return the curretn selected value of source select/combo
     */
    this.getValue = function(){
        return $('#'+src).val();
    }

    /**
	 * the function that triggers reload
     *
	 * @param url the URL from where the JSON is to be fetched
	 * @param prependSelect if '---SELECT XXX ---' is to be prepended to the options
	 */
    this.reloadChild = function(url, prependSelect){        
        // the url which queries the database
        var _url = url;

        // the params to be sent as POST varaiables the above URL
        var params ={
            // the task to be performed
            task: this.task,
            // id of the parent select/combo
            parent_id: this.getValue()
        };

        // make the AJAX call the above URL
        $.ajax({
            url: _url,
            type: 'POST',
            data: params,
            dataType: 'json',
            success: function(itemList){
                $('#'+target).empty();
                if(itemList.length > 0){
                    for(var n = 0; n < itemList.length; n++) {
                        $('#'+target).get(0).add(
                            new Option(itemList[n].name,itemList[n].id),
                            document.all ? 0 : null);
                    }
                }
                // if --Select XXX-- needs to prepended to the child select/combo
                if(prependSelect != null || prependSelect == true){
                    //$('#'+target).prepend('<option selected value="">--Select '+child.toString()+'--</select>')
                    $('<option value="">--- Select '+child.toString()+'--</option>').prependTo($('#'+target+':first-child'));
                    $('#'+target+' option[value=""]').attr('selected', 'selected');
                }
            },
            complete:function(){
                // the recursive handler which checks if there is any child element to reload
                if(!child.isLeaf){
                    child.reloadChild(url, prependSelect);
                }
            }
        });
        return false;
    }
}

/**
 * Blueprint for cloning.
 * This class also utilises the  $.format function of validate.js for use of placehilders.
 *
 * @author Abhishek<shresthabhishek@gmail.com>
 *
 * @param <int> cloneLimit the limit till which cloning is to be allowed
 * @param <string> msgDivId the id of the element where the message related to cloning is to be shown
 *
 */
function Cloner(cloneLimit, msgDivId){
    this.cloneLimit = cloneLimit;
    this.msgDiv = '#'+msgDivId;

    /**
     * clones and formats the node(s).
     * Also displays message on clone limt exceeded.
     *
     * @param <string> clonedSelector the selector that has been cloned
     * @param <string> cloneSrc the source for cloning
     * @param <string> cloneTarget the target before which the cloned elements are to be placed
     */
    this.clone = function(clonedSelector, cloneSrc, cloneTarget){
        var cloneCount = $(clonedSelector).length;

        if(cloneCount <= this.cloneLimit){
            var cloneContent = $('#'+cloneSrc).html();
            var outputClone = $.format(cloneContent, cloneCount);

            $(outputClone).insertBefore('#'+cloneTarget);
        }else{
            $(this.msgDiv).html('You cannot add more than '+cloneLimit+' items');
            $(this.msgDiv).fadeIn(400).fadeOut(4000);
        }
    }

    /**
     *
     * clones and formats the node(s)
     * Also displays message if minimum clone limit is reached.
     *
     * @param <string> clonedSelector the selector that has been cloned
     */
    this.remove = function(clonedSelector){
        var cloneCount = $(clonedSelector).size();

        if(cloneCount > 1){
            $(clonedSelector+':last').remove();
        }else{
            $(this.msgDiv).html('You must add at least 1 item.');
            $(this.msgDiv).fadeIn(400).fadeOut(4000);
        }
    }
}

function redirect(url){
    window.location = url;
}

function toCapsFirst(){
    $('.pronoun').blur(function(event){
        var text = event.target.value;
        var firstCharCode = text.charCodeAt(0);

        if(firstCharCode > 96 && firstCharCode < 123){ // deal only if small case
            var firstChar =  String.fromCharCode(text.charCodeAt(0)-32);
            event.target.value = firstChar + text.substr(1, text.length);
        }
    });
}

function back(){
    window.history.back();
}

function postAjax(url, data, successHandler){
    $.ajax({
        url: url,
        data: data,
        type: 'post',
        dataType: 'json',
        timeout: 5000,
        error: function(){
            $('message').val('Cannot connect to server at the moment!!!');
        //alert('error');
        },
        success: function(response){
            successHandler(response);
        }
    });
}

function alterFontSize(target, factor){
    var oldFontSize = parseInt(target.css('font-size'));
    
    if(factor < 0 && oldFontSize > 13 && oldFontSize <= 20){
        target.css('font-size', (oldFontSize + factor)+'px');
    }else if(factor > 0 && oldFontSize >= 13 && oldFontSize < 20){
        target.css('font-size', (oldFontSize + factor)+'px');
    }    
}
