/*
 *
 Utility Functions to facilitate JS Operations
 * @laze
 */
/*Inner HTML  HAAck*/

innerXHTML = function($source) {
    if (typeof $source == "string") {
        $source = document.getElementById($source);
    }
    //alert($source);
    if (!($source.nodeType == 1)) return false;
    var $children = $source.childNodes;
    var $xhtml = '';
    for (var $i=0; $i<$children.length; $i++) {
        if ($children[$i].nodeType == 3) {
            var $text_content = $children[$i].nodeValue;
            $text_content = $text_content.replace(/</g,'&lt;');
            $text_content = $text_content.replace(/>/g,'&gt;');
            $xhtml += $text_content;
        }
        else if ($children[$i].nodeType == 8) {
            $xhtml += '<!--'+$children[$i].nodeValue+'-->';
        }
        else {
            $xhtml += '<'+$children[$i].nodeName.toLowerCase();
            var $attributes = $children[$i].attributes;
            for (var $j=0; $j<$attributes.length; $j++) {
                var $attName = $attributes[$j].nodeName.toLowerCase();
                var $attValue = $attributes[$j].nodeValue;
                if ($attName == 'style' && $children[$i].style.cssText) {
                    $xhtml += ' style="'+$children[$i].style.cssText.toLowerCase()+'"';
                }
                else if ($attValue && $attName != 'contenteditable') {
                    $xhtml += ' '+$attName+'="'+$attValue+'"';
                }
            }
            $xhtml += '>'+innerXHTML($children[$i]);
            $xhtml += '</'+$children[$i].nodeName.toLowerCase()+'>';
        }
    }
	
    return $xhtml;
}

/////////////

/*LOAD COMBO*/
function populator(url){
    $.getJSON(url,function(itemList) {
        if(itemList){
            $.each(itemList, function(i, entry) {
                if($('#'+entry.name)){//If Element Exists
                    var typeElem = $('#'+ entry.name).attr('tagName')
                    if((typeElem=='INPUT')||(typeElem=='SELECT')||(typeElem=='TEXTAREA')){
                        $('#'+ entry.name).val(entry.value);
                    }else{
                        $('#'+ entry.name).html(entry.value);
                    }
                }
                else{//debug only...
                    alert(entry.name+' - doesnot exist in the form!');
                }
            
            });
        }
    });

}
function populatorSync(url){
    var itemList =getAjax(url);
    if(itemList){
        $.each(itemList, function(i, entry) {
            if($('#'+entry.name)){//If Element Exists
                var typeElem = $('#'+ entry.name).attr('tagName')
                if((typeElem=='INPUT')||(typeElem=='SELECT')||(typeElem=='TEXTAREA')){
                    $('#'+ entry.name).val(entry.value);
                }else{
                    $('#'+ entry.name).html(entry.value);
                }
            }
            else{//debug only...
                alert(entry.name+' - doesnot exist in the form!');
            }

        });
    }
}

function getAjax(iUrl){
    var itemList;
    $.ajax({
        url: iUrl,
        dataType:'json',
        async:false,
        success:function(data){
            itemList = data;
        }
    });
	
    return itemList;
}
function Combo(iUrl,iName){
    //Properties
    this.url = iUrl;
    this.options='<option value=>-----Select '+iName+'-----</option>';
    //this.optLen = 0;

    //Methods
    this.getList = function(){
        var itemList = getAjax(this.url);
        if(itemList){
            alert(itemList[0][id]);
            //alert (itemList.length);
            for(var n = 0; n < itemList.length; n++){
                //alert(itemList[n].id);
                this.options += '<option value="'+ itemList[n][0] +'">' + itemList[n][1] + '</option>';
            }
        }
    }
  
    this.getList(); //Minor Construct
    
    this.setList = function(iTarget,iSelect){
        //alert(iTarget);//Debug Line
        $(iTarget).empty();
        if(iSelect==null){
            $(iTarget).html(this.options);
        }else{
            var newOptions = this.options.replace('<option value="'+ iSelect +'">','<option value="'+ iSelect +' " selected="selected" >');
            $(iTarget).html(newOptions);
        }
    //$(this.targets).attr('optLen',this.optLen);
    }    
}

function Cloner(iElem,iTarget){    
	
   // if($.browser.msie){//IE HAck
    //    iElem = iElem.replace('#','');
   //     this.template=innerXHTML(iElem);
   // }else{
        this.template=$(iElem).html();
  //  }
    //this.template=$(iElem).html();
    this.counter=1;
    this.targets=iTarget;
   
    //Methods
    this.setClone = function (iElem){
        this.template=$(iElem).html();
    // alert(this.template);
    }

    this.Clone = function(paramsClone){
        //Debug Line
        if(paramsClone!=null){
            paramsClone.unshift(this.counter);
        }else{
            var paramsClone = new Array;
            paramsClone[0] = this.counter;
        }
        //alert("get"+paramsClone);
        var outputClone = $.format(this.template,paramsClone);
        //alert(this.targets+outputClone);
        //alert($(this.targets).html());
        //$(outputClone).appendTo(this.targets);
        //$(outputClone).appendTo('#abc');
        $(this.targets).append(outputClone);
        this.counter++;
        //regDateBox();
    }
    this.CRemove = function(maxValue){
        if(maxValue==null){
            maxValue = 1;
        }
        if(this.counter>parseInt(maxValue)){
            this.counter--;
            $(this.targets+' tbody[class=clone]:last').remove();
        }
    }
    this.CRemoveAll = function(){
        $(this.targets+' tbody[class=clone]').remove();
        this.counter=1;
    }
    this.CRemoveEverything = function(){ //remove everything except the header, we are expecting tbody in header row as well
        $(this.targets+' tbody').each(function(index,elm){
            if(index>0)
                $(this).remove();
        });
        this.counter=1;
    }
}
/**
 * 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 ComboLoader(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: 'GET',
            data: params,
            dataType: 'json',
            async:false,
            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){
                    /*
               this.getList = function(){            
                var itemList = getAjax(this.iurl);             
                if(itemList){
                    //this.optLen = itemList.length;                   
                    for(var n = 0; n < itemList.length; n++){
                        this.options += '<option value="'+ itemList[n].id +'">' + itemList[n].name + '</option>';
                        }
                    }
                }
                 this.getList(); //Minor Construct*/
                    //
                    //$('#'+target).prepend('<option selected value="">--Select '+child.toString()+'--</select>')
                   
                    //$('#'+target+' option[value=""]').attr('selected', 'selected');
                    $('<option value="" selected>--- Select '+child.toString()+'--</option>').prependTo($('#'+target+':first-child'));
                }
            },
            complete:function(){
                // the recursive handler which checks if there is any child element to reload
                if(!child.isLeaf){                    
                    child.reloadChild(url, prependSelect);
                }
            }
        });
        return false;
    }
    this.setCList = function(iTarget,iSelect,Url){
        this.reloadChild(Url, true);
        $(iTarget).val(iSelect);
    }
    
}

function regDateBox(dtFormat,dateBox){
    if(dtFormat==null){
        dtFormat="yy-mm-dd";
    }
    if(dateBox==null){
        dateBox="form .dateBox";
    }
    $(dateBox).datepicker({
        dateFormat:dtFormat,
        minDate:'-20Y',
        maxDate:'+20Y',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showAnim:'slideDown'
    });
}

function regDateBoxtr(dtFormat,dateBox){
    if(dtFormat==null){
        dtFormat="yy-mm-dd";
    }
    if(dateBox==null){
        dateBox="form .dateBox";
    }
    $(dateBox).datepicker({
        dateFormat:dtFormat,
        minDate:'-20Y',
        maxDate:'0',
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        showAnim:'slideDown'
    });
}

function regDialog(){
    $('#results').dialog({
        bgiframe: true,
        title:'Task Status',
        width:320,
        height:240,
        modal: true,
        autoOpen:false,
        buttons: {
            Ok: function() {
                $(this).dialog('close');
                $('#results').empty();
            }
        }
    });
}

/*Get Reloaded~Result*/
function getReload(grid){
    $(grid).trigger("reloadGrid");
    $('#results').dialog('open');
    $('#results').dialog('option', 'buttons', {
        "OK": function() {
            $(this).dialog('close');
            $(this).empty();
        }
    });
}
/*------------*/
function ComboRel(src, target, task, isLeaf, child, name, prependSelect){
    if(prependSelect == null){
        prependSelect = 'All';
    }
    this.src = src;
    this.target = target;
    this.task = task;
    this.isLeaf = isLeaf;
    this.options ='<option value=>-----Select '+prependSelect+'-----</option>';

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

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

    this.reload = function(){
        // the url which queries the database
        var url = 'getJsonFormat.php';

        // 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()
        };
        
        //alert(params.task +' : ' + params.parent_id);
        $.ajax({
            url: url,
            type: 'POST',
            data: params,
            dataType: 'json',
            success: function(itemList){
                $('#'+target).empty();
                for(var n = 0; n < itemList.length; n++) {
                    this.options += '<option value="'+ itemList[n].id +'">' + itemList[n].name + '</option>';
                }
                $('#'+target).html(this.options);
            },
            complete:function(){
                // the recursive handler which checks if there is any child element to reload
                if(!isLeaf){
                    child.reload();
                }
            }
        });
        return false;
    }
}
/*Ajaxify Modalify Validate as well [EDIT MODAL]-------------------*/
function frmMojax(grid,frm_name,frm_div,title,mheight,mwidth){
    if(mheight==null){ // default height
        mheight=300;
    }
    if(mwidth==null){ //  default width
        mwidth=275;
    }

    var reloadState = function (){
        $(frm_div).dialog('option', 'buttons', {
            "OK": function() {
                $(this).dialog('close');
            }
        });
        $(grid).trigger("reloadGrid");
    }
    var checker = function(){ //validate
        var v = $(frm_name).validate({
            onkeyup:false,
            onblur:false
        });
        if(v.form()){
            $(frm_div).dialog('option', 'buttons',{});
            $(frm_div).dialog('option', 'title','Task Status' );
            $(frm_div).html('Please Wait...');
            return true;
        }
        else{
            return false;
        }
    }
    $(frm_name).ajaxForm({
        target: frm_div,
        async:false,
        beforeSubmit:checker,
        success: reloadState,
        resetForm: true,
        clearForm:true
    });

    $(frm_div).dialog({
        bgiframe: true,
        autoOpen: false,
        height: mheight,
        width: mwidth,
        modal: true,
        close: function(){
            $(this).dialog('destroy');
        }
    });

    $(frm_div).dialog('option', 'title',title);

    $(frm_div).dialog('option', 'buttons', {
        "Cancel": function() {
            $(frm_div).dialog('close');
        },
        'Save': function() {
            $(frm_name).submit();
        }
    });
    $(frm_div).dialog('open'); //Modal Opener
    
}

function frmMojax1(frm_div,title,mheight,mwidth){
    if(mheight==null){ // default height
        mheight=300;
    }
    if(mwidth==null){ //  default width
        mwidth=275;
    }
    $(frm_div).dialog({
        bgiframe: true,
        autoOpen: false,
        height: mheight,
        width: mwidth,
        modal: true,
        close: function(){
            $(this).dialog('destroy');
        }
    });

    $(frm_div).dialog('option', 'title',title);

    $(frm_div).dialog('option', 'buttons', {
        "Cancel": function() {
            $(frm_div).dialog('close');
        }
    });
    $(frm_div).dialog('open'); //Modal Opener

}

/*Search Functions in the Main Grid*/
function prepareSearchBtn(urls,grid,patch){ //searchBtn,searchTxt|clear,search
    if(patch==null){
        patch='';
    }

    $('#searchBtn'+patch).click(function() { //Add Action to Search Button
        exploreGrid('search',urls,grid,patch);
    });

    $('#searchTxt'+patch).keypress(function(e) { //Add Action to Search Button
        if(e.which==13){
            exploreGrid('search',urls,grid,patch);
        }
    });

    $('#searchClrBtn'+patch).click(function() { //Add Action to Search Clear Button
        $('#searchTxt'+patch).val('');
        exploreGrid('clear',urls,grid,patch);
    });
}
function exploreGrid(mask,urls,grid,patch){//searchBtn,searchTxt|clear,search
    if(patch==null){
        patch='';
    }
    if(mask=='clear'){
        $(grid).setGridParam({
            url: urls,
            page:1
        }).trigger("reloadGrid");
    }
    else if(mask=='search'){
        var keywords = $('#searchTxt'+patch).val();
        if(keywords==''){
            $(grid).setGridParam({
                url: urls,
                page:1
            }).trigger("reloadGrid");
        }
        else{
            // Calling for Search Result on Server Side and Reloading grid with the result
            $(grid).setGridParam({
                url:urls+keywords,
                page:1
            }).trigger("reloadGrid");
        }
    }
}

/*---------------*/
/*Ajaxify Non-Paged Validate as well [Form]-------------------*/
function AjaxForm(grid,frm_name,frm_div,resp_div,frmType,cbFunc){
    if(resp_div==null){
        resp_div = '#results';
    }
    $(frm_div).show();
    if(!isNull(grid)){
        $(grid+"Div").hide();
    }
    var reloadState = function(ops){
        if(resp_div=='#results'){
            if(isNull(frmType)){
                $(frm_div).empty();
            }
            if(!isNull(frm_div)){
                $(frm_div).hide();
            }
            if(!isNull(grid)){
                $(grid+"Div").show();
            }

            $("#tables").show(); //if tab exists
            if(ops!='c'){
                $('#results').dialog('open');
            }
            $('#results').dialog('option', 'title','Task Status' );
            $('#results').dialog('option', 'buttons', {
                "OK": function() {
                    $(this).dialog('close');
                }
            });
        }else{
            $(resp_div).show();
        }
        if(!isNull(grid)){
            $(grid).trigger("reloadGrid");
        }
        if(isFunction(cbFunc)){
            cbFunc();
        }
    }
    $('.closer').click(function(){//Cancel Button Action
        reloadState('c');
    });

    var subs = function(){
        var specialRequest = 0;
        if($('input[name=downloadTrue]').fieldValue()=="1"){
            specialRequest = 1;
        }
        if(specialRequest == 0){
            $(frm_name).ajaxSubmit({
                async:false,
                target: resp_div,
                resetForm:true,
                success: reloadState
            });
        }else{
            frm_name.submit();
        }
    }
    var v = $(frm_name).validate({
        onkeyup:false,
        onblur:false,
        submitHandler:subs
    });
     setAsterisk(frm_name);
}
/*-----------*/
/*Ajaxify Paged Validate as well [ADD Tabbed Form]-------------------*/
function wizard(gridId,frmId,frmContainerId){
		
    reloadState = function(ops){
        $(gridId).trigger("reloadGrid");
        $(frmContainerId).hide();
        $(frmContainerId).empty();
        $(gridId+"Div").show();
        if(ops!='c'){
            $('#results').dialog('option', 'title','Task Status' );
            $('#results').dialog('option', 'buttons', {
                "OK": function() {
                    $(this).dialog('close');                                
                }
            });
            $('#results').dialog('open');
        }
    }
	
    $('.cancelwiz').click(function(){//Cancel Button Action
        reloadState('c');
    });
	
    $(frmId).formwizard({ //wizard settings
        formPluginEnabled: true,
        validationEnabled : true
    },
    {//validation settings
        debug:false,
        onkeyup:false,
        onblur:false
    },
    {// form plugin settings
        async:false,
        target: '#results',
        success: reloadState,
        resetForm:false
    });

    $(gridId+"Div").hide();
    $(frmContainerId).show();
    
	setAsterisk(frmId);
}
/*-----------------------*/
function wizardView(id,parent){
    this.id = id;
    this.parent = parent;
    this.page = 1;
    this.total = $('.step', id).length;
    //Hide all page
    $('.step',id).hide();
    $('.step',id).each(function(index,step){
        $(step).attr('id','steps_'+(index+1));

    });

    //Show First Step
    $('#steps_1').show();
    $(id).show();
    $(parent).hide();

    this.manageBtn = function(){
        $('#pageView').html(this.page);
        $('#pageTotal').html(this.total);

        if(this.page==1){
            $('#backBtn').hide();
        }else{
            $('#backBtn').show();
        }
        if(this.page==this.total){
            $('#nextBtn').hide();
        }else{
            $('#nextBtn').show();
        }
    }

    this.manageBtn();

    //Go Step Up
    this.stepBack = function(){
        if(this.page>1){
            $('#steps_'+this.page).hide();
            $('#steps_'+(--this.page)).show();
        }
        this.manageBtn();
    }

    //Go Step Down
    this.stepNext = function(){
        if(this.page<this.total){
            $('#steps_'+this.page).hide();
            $('#steps_'+(++this.page)).show();
        }
        this.manageBtn();
    }

    //Close View
    this.Close = function(){
        //alert(this.id+'-'+this.parent);
        $(this.id).hide();
        $(this.parent).show();
    }


}
/*--------------*/

function wizardViewSpecial(id,parent,frmId){
    this.id = id;
    this.parent = parent;
    this.page = 1;
    this.total = $('.step', id).length;
    //Hide all page
    $(this.parent+'Div').hide();
    $('.step',id).hide();
    $('.step',id).each(function(index,step){
        $(step).attr('id','steps_'+(index+1));
    });

    //Show First Step
    $('#steps_1').show();
    $(id).show();

    this.manageBtn = function(){
        $('#pageView').html(this.page);
        $('#pageTotal').html(this.total);

        if(this.page==1){
            $('#backBtn').hide();
            $('#submitBtn').hide();
        }else{
            $('#backBtn').show();
            $('#submitBtn').hide();
        }
        if(this.page==this.total){
            $('#nextBtn').hide();
            $('#submitBtn').show();
        }else{
            $('#nextBtn').show();
        }
    }


    this.manageBtn();

    //Go Step Up
    this.stepBack = function(){
        if(this.page>1){
            $('#steps_'+this.page).hide();
            $('#steps_'+(--this.page)).show();
        }
        this.manageBtn();
    }

    //Go Step Down
    this.stepNext = function(){
        if(this.page<this.total){
            $('#steps_'+this.page).hide();
            $('#steps_'+(++this.page)).show();
        }
        this.manageBtn();
    }

    //Close View
    this.Close = function(){       
        $(this.id).hide();
        $(this.parent+'Div').show();

    }
      var reloadState = function(){
            $(id).hide();
            $(parent).trigger("reloadGrid");
            $(parent).show();

            $(parent+"Div").show();
            $('#results').dialog('open');

            $('#results').dialog('option', 'title','Task Status' );
            $('#results').dialog('option', 'buttons', {
                "OK": function() {
                    $(this).dialog('close');
                }
            });
        
        }
       var subs = function(){
            var state = confirm('Are you sure? Do you want to continue?');
            if(state){
                $(frmId).ajaxSubmit({
                    async:false,
                    target: '#results',
                    success: reloadState,
                    resetForm:false
                });
            }
        }
        var v = $(frmId).validate({
            onkeyup:false,
            onblur:false,
            submitHandler:subs
        });


}



//usage return confirmMessage(dialogMsg);
function confirmCommit(msg,commitField){
    if(confirm(msg)){
        $(commitField).val("1");
        return true;
    }else{
        return false;
    }
}
function strToDate(stin){
    if(stin!=null){
        var month = parseInt(stin.substring(0,2),10);
        var day = parseInt(stin.substring(3,5),10);
        var year = parseInt(stin.substring(6,10),10);
        var dateReturn = new Date();
        dateReturn.setFullYear(year);
        dateReturn.setMonth(month-1);
        dateReturn.setDate(day);
        return dateReturn;
    }
}
/*-----------*/
function tArea(classUsed,toolBar){
    this.classUsed = classUsed;
    this.elements = new Array();
    this.tAInstance = new Array();
    if(toolBar==null){
        this.toolBar = "Normal";
    }else{
        this.toolBar = toolBar;
    }
    //alert(this.toolBar);

    this.initTArea = function(){
        this.cleanUP();
        var newArr = new Array();
        $(this.classUsed).each(function(i,elem){
            newArr.push(elem.id);
        });
        this.elements = newArr;
    //alert(this.elements+'='+this.elements.length);
    }

    this.loadTArea = function(width,height){
        if(isNull(width)){
            width = '500px';
        }
        if(isNull(height)){
            height = '450px';
        }
        var tAreaTmp = new Array();
        var myBar = this.toolBar;

        $(this.elements).each(function(i, elem){
            tAreaTmp.push(CKEDITOR.replace(elem, {
                toolbar: myBar,
                width: width,
                height: height
            }));
        });
        
        this.tAInstance = tAreaTmp;

    }

    this.cleanUP = function(){
        $.each(this.tAInstance, function(i,item){
            if(item)
                CKEDITOR.remove(item);
        });
    }

    this.clearData = function(){
        $.each(this.tAInstance, function(i,item){
            if(item)
                item.setData('');
        });
    }

    this.saveReady = function(){
        var dataArr = this.elements;
        $(this.tAInstance).each(function(i, elem){
            var tmpData = elem.getData();
            $("#"+dataArr[i]).val(tmpData);
            $("#"+dataArr[i]+'_Div').html(tmpData);

        });
    }


}

/*---------------------*/
function setAsterisk(formID){    
    $(formID+' .required').each(function(key,element){
        //$('#'+element.id).parent().parent().find('label').append("<span class='red'>*</span>");
        //alert ($('#'+element.id).parent('label').attr('tagName'));
        $('#'+element.id).prev('label').append("<span style='color:red'>*</span>");
    });
        $('.lAsterisk').append("<span style='color:red'>*</span>");
}

/*-----------*/


function paging(page, limit, url, container){
    //alert(from+' '+limit);
    var params = {
        from : page,
        limit: limit
    };

    $.ajax({
        url: url,
        data:params,
        success:function(data){
            $(container).html(data);
        }
    });
}

