$.fn.loadList = function(data, callback) {
    var list = $(this);
    list.val(0);
    callback = (callback == null)? function(){}: callback;
    return this.each(function() {

        if ( gdmcms.isJson(data)){
            list.addItems(data);
            callback.call();    
        }else{
            $.getJSON(data, null, function(data) {
                list.addItems(data);
                callback.call();
            });
        }
    });
};
    
$.fn.addItems = function(data) {
    return this.each(function() {
        itemOptions = "<option value='0'>-- Select an option --</option>";
        $.each(data, function(index, itemData) {
            itemOptions += "<option value='" + itemData.value+ "'> " +itemData.text + "</option>";
        });
        $(this).html(itemOptions);
    });
};

$.fn.setSortable= function() {
    grid =$(this);
    console.log(grid);
    movebutton =  grid.find('[title="Delete"]:first').clone().attr("title","Move");
    movebutton.find('.ui-icon').removeClass().addClass('ui-icon ui-icon-arrowthick-2-n-s move').attr("onclick","").attr("onClick","").attr("href","");
    grid.find('[title="Delete"]').after(movebutton);
    grid.find("td").each(function(){
        $(this).width( $(this).width() );
    });
    grid.find("tbody:first").sortable({ 
        axis: 'y',
        handle: '[title="Move"]',
        stop: function(event, ui) { 
            order = 1;
            rows = new Array();
            $(this).find("tr").each(function(index, value){
                rowId = $(this).attr('id');
                if (rowId != undefined){
                    row=new Object();
                    row.id =  rowId;
                    row.order =  index;
                    rows[index] =row;
                }
            });
            gdmcms.showMsgBox("Saving","Updataing order", MSG_INFO);
            orderObj = {
                rows: rows,
                order:true
            };
            callingGrid= grid;
            $.ajax({
                type: 'POST',
                url: '?callback=true',
                data: orderObj,
                success: function( data ) {
                    data =  jQuery.parseJSON( data );
                    gdmcms.showMsgBox("Saving", data.mesg,  data.type );
                    callingGrid.trigger("reloadGrid");
                }
            });
        }
    });
        
}

$.fn.toTextField = function() {
    $(this).replaceWith('<input type="text" id="' + $(this).attr('id') + '" name="' + $(this).attr('name') + '"/>');
}

$.fn.toCombo = function(url) {
    $(this).replaceWith('<select id="' + $(this).attr('id') + '" name="' + $(this).attr('name') + '"></select>');
    if (url!=undefined){
        $('#'+$(this).attr('id')).loadList(url);
    }
}

$.fn.getHiddenDimensions = function(includeMargin) {
    var $item = this,
    props = {
        position: 'absolute', 
        visibility: 'hidden', 
        display: 'block'
    },
    dim = {
        width:0, 
        height:0, 
        innerWidth: 0, 
        innerHeight: 0,
        outerWidth: 0,
        outerHeight: 0
    },
    $hiddenParents = $item.parents().andSelf().not(':visible'),
    includeMargin = (includeMargin == null)? false : includeMargin;
 
    var oldProps = [];
    $hiddenParents.each(function() {
        var old = {};
 
        for ( var name in props ) {
            old[ name ] = this.style[ name ];
            this.style[ name ] = props[ name ];
        }
 
        oldProps.push(old);
    });
 
    dim.width = $item.width();
    dim.outerWidth = $item.outerWidth(includeMargin);
    dim.innerWidth = $item.innerWidth();
    dim.height = $item.height();
    dim.innerHeight = $item.innerHeight();
    dim.outerHeight = $item.outerHeight(includeMargin);
 
    $hiddenParents.each(function(i) {
        var old = oldProps[i];
        for ( var name in props ) {
            this.style[ name ] = old[ name ];
        }
    });
 
    return dim;
}


$.fn.checkIcon = function() {
    $(this).each(function(){
        icon = ($(this).is(":checked")) ? 'ui-icon-check':'ui-icon-closethick';
        $(this).button({
            text: false,
            icons: {
                primary:icon
            }
        }).click(function(){
            icon = ($(this).is(":checked")) ? 'ui-icon-check':'ui-icon-closethick';
            $(this).button( "option", "icons", {
                primary:icon
            } );
                    
        })
    })
}

$.fn.isChildOf = function(exp){
    return $(this).parents().filter(exp).length>0;
}; 

$.fn.fadeInHTML = function(text) {
    $(this).data("innerText",text);
    $(this).fadeOut("fast",function(){
        text = $(this).data("innerText");
        $(this).data("innerText","");
        $(this).html(text);
        $(this).fadeIn("fast");
 
    });
};

var cache = [];
jQuery.fn.preLoadImages = function(){
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
        var cacheImage = document.createElement('img');
        cacheImage.src = arguments[i];
        cache.push(cacheImage);
    }
};

$.tools.validator.fn("[gdm_password]", "You password must be 8 characters or longer", function(input, value) { 
    return (value.length >= 8);
});
