function writeMessage(message){
    jQuery('#message').empty().addClass( 'msgCompl' ).removeClass( "msgWarn" ).append(message).show().fadeOut(25000);
}

function writeWornMessage(message){
    jQuery('#message').empty().addClass( 'msgWarn' ).removeClass( "msgCompl" ).append(message).show();
}

//function cleanMessageClass(){
//    jQuery('#message').removeClass( class )
//}

function hideMessage(){
    jQuery('#message').hide();
}

function getDummyValue(){
    var random = Math.random();
    var retval = new Date().getTime() / (random != 0 ? random : 1);

    return Math.round( retval );
}

function log(s){
    if (console) console.debug(s);
    else document.write(s);
}

function random(){
    return Math.floor(Math.random()*1000000);
}


//    /**
//     * slide up and slide down elements
//     * @param String id
//     */
//    function more(id) {
//        if ($(id).style.display=='none') {
//            new Effect.SlideDown($(id), {duration: 0.3});
//        } else {
//            new Effect.SlideUp($(id), {duration: 0.3});
//        }
//    }

function testPassword(){
//    hideMessage();
    jQuery('#loginEr, #loginEmailEr, #loginPassEr').hide();
    var l = $("login").value;
    var p = $("password").value;

    if (!l || l.length == 0){
        jQuery('#loginEmailEr').show();
        return;
    }

    if (!p || p.length == 0){
        jQuery('#loginPassEr').show();
        return;
    }
    var rem = $("rememberMe").checked;
    
    dwrService.checkLogin(l, p, rem, function (res){
        if (res && res.correct) {
            if (res.us) {
                createCookie("us", res.us, 30);
                createCookie("has", res.has, 30);
            }
            if (!formTargertURI) formTargertURI = appPath;
            location.href = formTargertURI;
        }
        else {
            jQuery('#loginEr').show();}
    });
}

function replaceNewLinesWithPageBreaks( source )
{
    return source.replace( /\n/g, "<br/>" );
}

function comparePasswords(){

    if ($('password').value != $('password1').value){
        writeWornMessage('Passwords not same');
        return false;
    }

    if ($('password').value.length<5){
        writeWornMessage('Password must be more than 5 characters');
        return false;
    }
    return true;
}

function goNewUser() {
    location.href = appPath+'NewUser';
}

function checkemail(str){
    var filterEmail = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9_\.\-])+\.)+([a-zA-Z]{2,4})+$/;
    return filterEmail.test(str);
}

function hex2Dec(hex) {
    return parseInt(hex,16);
}

function dec2Hex(dec){
    // The allowed hex characters
    var hexChars = '0123456789ABCDEF';
    if (isNaN(dec)) {
        return 0;
    }
    // Get the first hex character
    var hexNumber = hexChars.substr(dec & 15, 1);
    // Loop through and get the rest of the hex characters
    while (dec > 15) {
        // Shift the bits to the right
        dec >>= 4;
        // Get the hex value
        hexNumber = hexChars.substr(dec & 15, 1) + hexNumber;
    }
    while (hexNumber.length < 6) {
        hexNumber = '0' + hexNumber;
    }
    return hexNumber;
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

function getElementPosition(elem){
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
    var l = 0;
    var t = 0;
    while (elem)
    {
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }
    return {"left":l, "top":t, "width": w, "height":h};
}

function hideModal(){
    id=jQuery('#modalWindowBg').attr( 'modalW');
    jQuery('#'+id).hide();
    jQuery('#modalWindowBg').hide();
}

function showModal(id) {
    var _docHeight = Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight);
    var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    if(window.innerHeight > _docHeight){ _docHeight = window.innerHeight;}
    if (!$('modalWindowBg')){
        jQuery('body').append('<div id="modalWindowBg"/>')
    }
    jQuery('#modalWindowBg').height( _docHeight ).width(_docWidth );
    jQuery('#modalWindowBg').attr( 'modalW', id ).show();
    var win=$(id);
    var vscroll = (document.all ? document.documentElement.scrollTop : window.pageYOffset);
    var clientHeight = (document.all ? document.documentElement.clientHeight : window.innerHeight);
    winH=jQuery("#"+id).height();
    winW=jQuery("#"+id).width();
    if (winH+10>_docHeight){
        jQuery('#modalWindowBg').height( winH+10 );
    }
    var h = (clientHeight  - winH)/2;
    if (h<0) h=10;
    win.style.top = (h + vscroll) + "px";
    win.style.left = ((_docWidth - winW) / 2) + "px";
    win.style.display = 'block';
}

function createPreviewWindow(id, h, w, flash){
    var divName='fullPreviewDiv';
    w1=w+10;
    h1=h+65;
    if (!$(divName)) {
        jQuery('body').append('<div id="'+divName+'" class="modalWindow"/>');
    }
    var src=appPath + 'GenerateChart?id=' + id + '&dummy=' + random();
    var htmlChart=appPath+'internal/CreateHtml?chartId=' + id;
    var img = '<IMG src="' + src + '">';
    if (flash){
        img ="<embed src='"+appPath+"chart.swf?data="+appPath+"GenerateFlash?id="+id+"&dummy=" + random()+"' quality='high' allowScriptAccess='always' width='"+w+"px' height='"+h+"px' type='application/x-shockwave-flash' pluginspage='http://www.macromedia.com/go/getflashplayer'/>";
    }
    var note= '<div class="smallText"><p class="info" id="htmlHint"><b>Note:</b>You can <a href="'+htmlChart+'">generate html</a> code for inserting in your page.</p></div><br/>' +
              '<a class="aButton" href="javascript:hideModal();"><span title="Close">Close</span></a>';
//    var flash=
    var result=img+"<br/>"+note;
    jQuery('#'+divName).html(result).height(h1).width(w1);
    showModal(divName);
}

function showHtmlLink(res){
    jQuery('#htmlHint').append()
}

function setBoxHexColor(id, color){
    $(id).style.backgroundColor = '#' + color;
    $(id).val = color;
}

function setBoxColor(id, color){
    var color1=dec2Hex(color);
    setBoxHexColor(id, color1);
}

function createCookie(name,value,days) {
	var expires = "";
    if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function logOff(){
    dwrService.logOff(function () {
        deleteCookie("has");
        location.href = appPath;
    });
}

function deleteCookie( name ) {
document.cookie = name + "=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function errHandler(msg, n) {
//    if (n && n.javaClassName && n.javaClassName == 'java.lang.SecurityException') {
//        //                alert("you are not logged in ="+msg);
//        //                prevId = getActiveModalWindow();
//        showModal('loginWindow');
//    } else {
        alert("Some errors on the page. Please relogin. ");
        //todo dwr log

//    }
}


function addCalendar(query, val){
    if (val){
        jQuery(query).val(val);
    }
    jQuery(query).addClass("embed").datepicker({
            dateFormat: "yy-mm-dd",
            showOn: "both",
            showButtonPanel: true,
            buttonImage: appPath+"img/calendar.gif",
            buttonImageOnly: true,
            changeMonth: true,
			changeYear: true
        });
}

function removeCalendar(query){
   jQuery(query).removeClass("embed").datepicker( 'destroy' ); 
}