/**
This file containes common function used in system
*/

var js_messages = [];

jQuery.fn.exists = function() { return (this.length > 0); };
jQuery.fn.loadNCache = function(url) { 
    if($('body').data(url)){
        $(this).html($('body').data(url));
        return;
    }
    
    $(this).html('<span class="wait">loading...</span>').load(url, function(data){
        $('body').data(url, data);
    });
};

//register the tasks at document load
$(document).ready(function(){
    
	 //register form submit
    $('form.validate').validationEngine({
           success :  false,
           failure : function() {}
    });
    
    window.setTimeout('show_js_errors()', 100);
    
    $("#dialog").dialog({
          'close' : function(event, ui){
             //window.location.reload();  
           },
           'show': "fade",
           'hide': "fade",
           'bgiframe': true,
           'autoOpen': false,
           'height': 'auto',
           'width': 900,
           'modal': true,
           'title': 'GetAWeb',
               
           'buttons': {},
           'position':{'of':$("#scroll_container"),"at":'top','my':'top'}
    });   
    
    $("#dialog").parent().appendTo($("#scroll_container"));
    $("#dialog").dialog("widget").draggable( "option", "containment","parent" );
   
});

function show_js_error(caller, message, type, ajaxed){
    js_messages.push({
        'caller': caller,
        'message': message,
        'type': type,
        'ajaxed': ajaxed
    });
}

function show_js_errors(){
    for(var i=0; i <js_messages.length; i++){
        $.validationEngine.buildPrompt(js_messages[i].caller,
                            js_messages[i].message,
                            js_messages[i].type,
                            js_messages[i].ajaxed
        );
    }
}

/**
* function used to post variables through javascript
*/

function postForm(url, vars)
{
    var form = document.createElement('form');
    form.method = 'post';
    form.action = url;

    for(var fieldname in vars)
    {
        var input = document.createElement('input');
        input.type='hidden';
        input.name=fieldname;
        input.value=vars[fieldname];
        form.appendChild(input);
    }
    
    document.body.appendChild(form);
    
    form.submit();
}

function debug(msg, clear){
    if(clear)
        log("clear");
    log("msg");
}                     

/**js timings **/
function tickTime(){
    var basetime = parseInt($("#timeinfo span").attr('basetime'));
    var date = new Date(basetime * 1000);
    $("#timeinfo span").html(date.toUTCString());
    $("#timeinfo span").attr('basetime', basetime+1);
}

function openDlg(options){
    options = $.extend(true,{'w':600, 'h': 'auto', 'u':null, 'i':false, 'd':'', 't':'', 'c':false, 'm':true, 'top':null
                ,'b': {}
                }
                 ,options   
                );

    $('#dialog').dialog('option', 'height', options.h);
    $('#dialog').dialog('option', 'width', options.w);
    $('#dialog').dialog('option', 'title', options.t);
    $('#dialog').dialog('option', 'modal', options.m);
    $('#dialog').dialog('option', 'buttons', options.b);
         
    if(options.i){
        $("#dialog").dialog("open").html("<iframe style='width:100%;height:100%;border:0px none;' src='"+options.u+"'>");   
    }else if(options.u){
        if(options.c){
            $("#dialog").dialog("open").loadNCache(options.u);
        }else{
            $("#dialog").dialog("open").load(options.u).html("<span class='wait'>Loading...</span>");
        }
    }else{
        $("#dialog").dialog("open").html(options.d);   
    }
    
    if(options.top == null){
        /*var top = ($("#scroll_container").scrollTop() + 20)+'px'; 
        $("#dialog").parent().css('top',top);*/
        $("#dialog").dialog('option', 'position', 'center');
    }else{
        $("#dialog").parent().css('top',options.top);
    }
    $(".ui-widget-overlay").appendTo($("#scroll_container")).height($("#content-box").height());
  
}

function openDialog(url,w,h,t,c){
    openDlg({'w':w, 'h':h, 'u':url, 't':t, 'c':c})
}

function openDialogData(htmldata,w,h, t,c){
   openDlg({'w':w, 'h':h, 'd':htmldata, 't':t, 'c':c})
}

function openDialogIframe(url,w,h,t,c){
    openDialogData("<iframe style='width:100%;height:100%;border:0px none;' src='"+url+"'>", w, h,t,c);
}

function closeDialog(){
  
    //$("#dialog").html("Loading...");
    $('#dialog').dialog('close');
    
}

jQuery.Validation = {
    is_empty: function(text) {
        return ( jQuery.trim(text).length == 0 || text == null || text == undefined) ;
    },
    is_email: function(email) {
        return ( email.match(/^[A-Za-z0-9\._\-+]+@[A-Za-z0-9_\-+]+(\.[A-Za-z0-9_\-+]+)+$/)) ;
    },
    is_number: function(num) {
        return ( num.match(/^[0-9]+$/)) ;
    },
    is_double: function(num) {
        return ( num.match(/^[0-9]*\.[0-9]*$/)) ;
    }
};

function isFunction(funcName){
    return eval("typeof " + funcName + " == 'function'");
}

function getNextID(){
    return new Date().getTime();
}

var savetimer = 0;
var anychanges = false; 
function saveWork(change){
    if(savetimer > 0){
        clearTimeout(savetimer);
    }
    if(change != undefined && change == true){
        anychanges = true;
    }
    
    if(!anychanges) return false;
    
    savetimer = window.setTimeout(function(){
        $(".ui-resizable").resizable('destroy');
        $('div.elewrapper').remove();
	//$('#navigator').parent().remove();
	
        do_image_dragable(true);
        //$("div.getaweb-splitpane-2 > div:first").resizable('destroy');
	var menu_html = $("#main-navigation-links").html();
	var second_menu_html = $("#second-main-navigation-links").html();
	var top_menu_html = $("#top-main-navigation-links").html();
	var footer_menu_html = $("#footer-main-navigation-links").html();
	
        var html = $("#contents").html();
	
	
        html = escape(html);
	menu_html = escape(menu_html);
	second_menu_html = escape(second_menu_html);
	top_menu_html = escape(top_menu_html);
	footer_menu_html = escape(footer_menu_html);
	
        $.post(URL_SITE+"/home/updateContent",{"elem" : html, "menu_elem" : menu_html, "second_menu_elem" : second_menu_html, "top_menu_elem" : top_menu_html, "footer_menu_elem" : footer_menu_html}, function(data){
	    
	    make_split_pane();
            do_image_dragable();
        });
        anychanges = false;
    }, 3000);
    
}

function runCommand( D, K) {
    var B = document;
    var H = $(currentEditableBox);
    if (!H) {
        return false
    }
    if (currentSel) {
        restoreSelection(currentSel.range);
        //currentSel = ""
    }
    switch (D) {
    case "increasefontsize":
        try {
            var J = B.queryCommandValue("FontSize");
            if (!J) {
                return B.execCommand("FontSize", false, 3)
            } else {
                if (typeof(J) == "string") {
                    if (J.match("px")) {
                        var F = pxToFontSize(parseInt(J.replace("px", "")))
                    } else {
                        var F = parseInt(J)
                    }
                    F = F > 6 ? 7 : F + 1;
                    return B.execCommand("FontSize", false, F)
                } else {
                    return B.execCommand("FontSize", false, J > 6 ? 7 : J + 1)
                }
            }
        } catch(G) {
           return B.execCommand(D, false, K)
        }
        break;
    case "decreasefontsize":
        try {
            var J = B.queryCommandValue("FontSize");
            if (!J) {
               return B.execCommand("FontSize", false, 1)
            } else {
                if (typeof(J) == "string") {
                    if (J.match("px")) {
                        var F = pxToFontSize(parseInt(J.replace("px", "")))
                    } else {
                        var F = parseInt(J)
                    }
                    F = F > 1 ? F - 1 : 1;
                   return  B.execCommand("FontSize", false, F)
                } else {
                   return  B.execCommand("FontSize", false, J < 2 ? 1 : J - 1)
                }
            }
        } catch(G) {
            return B.execCommand(D, false, K)
        }
        break;
    case "justifyleft":
        currentAlign = "left";
        H.css('textAlign', 'left');
        break;
    case "justifycenter":
        currentAlign = "center";
        H.css('textAlign', 'center');
        break;
    case "justifyright":
        currentAlign = "right";
        H.css('textAlign', 'right');
        break;
    case "justifyfull":
        currentAlign = "justify";
        H.css('textAlign', 'justify');
        break;
    /*case "insertorderedlist":
    case "insertunorderedlist":
        if (Prototype.Browser.IE) {
            focusEditBox();
            var E = document.selection.createRange();
            if (!E.htmlText) {
                E.pasteHTML("_");
                E.select()
            }
            E.execCommand("bold");
            $(E.parentElement()).wrap("p", {
                id: "getaweb-temp-p"
            });
            B.execCommand(D, false, K);
            var I = $("getaweb-temp-p");
            var C = I.select("strong")[0];
            I.update(C.innerHTML == "_" ? "": C.innerHTML);
            clean();
            return
        }*/
    default:
        return B.execCommand(D, false, K);
        break
    }
    //focusEditBox()
}
/**
function focusEditBox() {
    var C = $(currentBox);
    if (Prototype.Browser.IE) {
        var B = $("scroll_container");
        var A = B.scrollTop;
        C.setStyle({
            position: "fixed"
        });
        C.focus();
        C.setStyle({
            position: "relative"
        });
        B.scrollTop = A
    } else {
        C.focus()
    }
}

**/

function loadImage(imgObj, imgUrl){
    var img = new Image();
    $(imgObj).addClass('wait');
    var imgId = $(this).attr("id");
    var height = $(imgObj).height();
    var width = $(imgObj).width();
    $(imgObj).attr('src', URL_SITE+'assets/images/x.gif');
    $(imgObj).height(height);
    $(imgObj).width(width);
    $(img).load(function(){
        $(imgObj).removeClass('wait');
        $(imgObj).attr("src", img.src);
        $(imgObj).height('auto');
        $(imgObj).width('auto');
    }).attr({
        src: imgUrl
    });
    //$(img).remove();
}

function log(data){
    if(!$("#log-window").exists()){
        $('body', document).append('<div id="log-window" style="display: block; position:fixed; z-index:1102; border: 2px solid gray; bottom:0; right:20px; border: 1px solid %555555; overflow: auto; width: 300px; height:400px;background:#ffffff;"></div>');
        //alert(data);
    }
    
    if(data == "clear"){
        $("#log-window").html('');
    }else{
        $("#log-window").append('<span>'+data+'</span><br/>');
    }
}

function show_msg(msg, w, h){
    if(w == undefined) w = 300;
    if(h == undefined) h = 150;
    
    var top = ($("#scroll_container").scrollTop() + 20)+'px';
    openDlg({'d':msg,'m':true,'b':null,'w':w,'h':h,'top':top});
}
function mainfunc (func){
    //arguments.shift();
    this[Array.prototype.shift.call(arguments)].apply(this, arguments);
}
function launchSubscribe(type){
    if(URL_LOGGED_IN){
        show_upgrade_form();
    }else{
        popup_login();
    }
}

function show_upgrade_form(){
    window.open(URL_SITE+"/home/upgrade","upgrade","width=866, height=600,toolbar=0, status=0");
}
function popup_register(){
   $("#dialog").dialog('option', 'position', 'center');
   openDlg({w:575, h: 350, u:URL_SITE+"user/getregister", i:true, t: 'Create a new account', m:true});
}
function popup_login(){
   $("#dialog").dialog('option', 'position', 'center');
   openDlg({w:375, h: 300, u:URL_SITE+"user/ajaxlogin", i:false, t: 'Login', m:true});
}
