/**
 * Shows messages with appropriate styles
 */
function showMessages(msgs, close)
{
    // if no messages and we need to close the window
    if (!msgs.length && close) {
        winClose();
    }
    
    // init defaults
    jQuery.jGrowl.defaults.position = 'top-center';
    jQuery.jGrowl.defaults.closeTemplate = 'x';
    jQuery.jGrowl.defaults.closerTemplate = '<div>[ '+L['hide-all']+' ]</div>';
    
    // if we need to close popup after messages
    var params = {};
    if (close) {
        params['close'] = winClose;
    }
    
    for(var i = 0; i < msgs.length; i++) {
        params['sticky'] = true;
        params['theme'] = '';
        switch(msgs[i]['code'].toString().substring(0, 1)) {
            case '1':
                params['theme'] = 'jmsg-alert';
                break;
            case '2':
                params['sticky'] = false;
                params['theme'] = 'jmsg-success';
                break;
            case '3':
            case '4':
                params['theme'] = 'jmsg-error';
                break;
        }
        $.jGrowl(msgs[i]['msg'], params);
    }
}

/**
 * Submits form and sets flag of apply
 */
function applyForm(form) 
{
    $(form).append($('<input type="hidden" name="apply" value="1" />')).submit();
}

/**
 * Switches loading panel
 */
function loading(action)
{
    if (!$('#loadingPanel').length) {
        $('<div id="loadingPanel"><div></div><p><b>'+L['loadingPanel']+'</b><span><em></em></span></p></div>').appendTo(document.body);
        setInterval(function () {
            var e = $('#loadingPanel em');
            if (e.attr('xpos') == undefined) {
                e.attr('xpos', -52);
            }
            var pos = 1*e.attr('xpos')+3;
            if (pos > 200) {
                pos = -52;
            }
            e.attr('xpos', pos);
            e.css('left', pos+'px');
        }, 50);
    }
    if (action == undefined) {
        action = $('#loadingPanel:visible').length ? false : true;
    }
    if (action) {
        $('#loadingPanel').fadeIn();
    } else {
        $('#loadingPanel').fadeOut();
    }
}


/**
 * Window Management
 */
function winOpen(href, width, height, name)
{
    if (!width) {
        width = 10;
    }
    if (!height) {
        height = 10;
    }
    if (!name) {
        name = 'blank_'+Math.floor(Math.random()*100000);
    }
    var params = 'scrollbars=1,resizable=yes,status=1,width='+width+',height='+height;
    var win = window.open(href, name, params);
    win.isPopup = 1;
}
function winResize(w, h, force)
{
    if (window.isPopup || force) {
        window.resizeTo(w, h);
    }
}
function winClose()
{
    window.close();
}
function winReload()
{
    // reload page without re-POSTing parameters
    window.location = window.location.href;
}

/**
 * Cookies management
 */
function setCookie(c_name, value, expiredays, path)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    if (path == '') { path = '/'; }
    document.cookie = c_name + "=" + escape(value)+ ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString()) + ';path=' + escape(path);
}
function getCookie(c_name)
{
    if (document.cookie.length > 0) {
        c_start=document.cookie.indexOf(c_name + "=");
        
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            
            if (c_end == -1) { 
                c_end = document.cookie.length;
            }
            
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    
    return "";
}

/**
 * Calculates period from current time
 */
function calcPeriod(type, currentTime) 
{
    period = new Array();
    period['startDate'] = '';
    period['startTime'] = '00:00:00';
    period['stopDate']  = '';
    period['stopTime']  = '23:59:59';
    
    if (currentTime == undefined) {
        cur_dt = new Date();
    } else {
        cur_dt = new Date(currentTime*1000);
    }
    
    stop_dt  = new Date(cur_dt);
    start_dt = new Date(cur_dt);
    
    switch(type) {
        case 'curYear':
            start_dt.setDate(1);
            start_dt.setMonth(0);
            stop_dt = new Date(start_dt);
            stop_dt.setYear(stop_dt.getFullYear()+1);
            stop_dt.setDate(stop_dt.getDate()-1);
        break;
        case 'prevYear':
            start_dt.setYear(start_dt.getFullYear()-1);
            start_dt.setDate(1);
            start_dt.setMonth(0);
            stop_dt = new Date(start_dt);
            stop_dt.setYear(stop_dt.getFullYear()+1);
            stop_dt.setDate(stop_dt.getDate()-1);
        break;
        case 'curMonth':
            start_dt.setDate(1);
        break;
        case 'prevMonth':
            start_dt.setDate(1);
            start_dt.setMonth(start_dt.getMonth()-1);
            stop_dt = new Date(start_dt);
            stop_dt.setMonth(stop_dt.getMonth()+1);
            stop_dt.setDate(stop_dt.getDate()-1);
        break;
        case 'curWeek':
            dow = cur_dt.getDay();
            if (dow == 0) { dow = 7; }
            start_dt = new Date(cur_dt.getTime() - (dow-1)*24*3600*1000);
        break;
        case 'prevWeek':
            dow = cur_dt.getDay();
            if (dow == 0) { dow = 7; }
            start_dt = new Date(cur_dt.getTime() - (dow-1)*24*3600*1000);
            start_dt.setDate(start_dt.getDate()-7);
            stop_dt = new Date(start_dt);
            stop_dt.setDate(stop_dt.getDate()+6);
        break;
        case 'curDay':
        break;
        case 'prevDay':
            start_dt.setDate(start_dt.getDate()-1);
            stop_dt = new Date(start_dt);
        break;
    }
    
    period['startDate'] = printf('%04d-%02d-%02d', start_dt.getFullYear(), start_dt.getMonth()+1, start_dt.getDate());
    period['stopDate']  = printf('%04d-%02d-%02d', stop_dt.getFullYear(),  stop_dt.getMonth()+1,  stop_dt.getDate());

    return period;
}

/**
 * Parse of URLs querystring
 */
jQuery.query = function(q) {
    var r = {};
    q = unescape(q);
    q = q.replace(/^\?/,''); // remove the leading ?
    q = q.replace(/\&$/,''); // remove the trailing &
    jQuery.each(q.split('&'), function(){
        var key = this.split('=')[0];
        var val = this.split('=')[1];
        // convert floats
        if(/^[0-9.]+$/.test(val))
        val = parseFloat(val);
        // ingnore empty values
        if(val || val === 0)
        r[key] = val;
    });
    
    return r;
};

/**
 * Checks if form differs from default values
 */
jQuery.isFilled = function (form) {
    var _as = $($(form).serializeArray()).filter(function (i, field) {
        // check if it is default params
        var el = $('#I-advsearch > form *[name="'+field.name+'"]');
        var tagName = el.prop('tagName');
        
        // first we skip any hidden object
        if (tagName == 'INPUT' && el.attr('type') == 'hidden') {
            return false;
        }
        
        // then we skip select value is its first
        if (tagName == 'SELECT') {
            if (field.value == el.find('option:nth-of-type(1)').val()) {
                return false;
            }
        }

        return field.value != '';
    });
	return _as.length > 0;
}


/**
 * Formats string for output
 */
function printf(fstring)
{ var pad = function(str,ch,len)
      { var ps='';
        for(var i=0; i<Math.abs(len); i++) ps+=ch;
        return len>0?str+ps:ps+str;
      }
    var processFlags = function(flags,width,rs,arg)
      { var pn = function(flags,arg,rs)
          { if(arg>=0)
              { if(flags.indexOf(' ')>=0) rs = ' ' + rs;
                else if(flags.indexOf('+')>=0) rs = '+' + rs;
              }
            else
                rs = '-' + rs;
            return rs;
          }
        var iWidth = parseInt(width,10);
        if(width.charAt(0) == '0')
          { var ec=0;
            if(flags.indexOf(' ')>=0 || flags.indexOf('+')>=0) ec++;
            if(rs.length<(iWidth-ec)) rs = pad(rs,'0',rs.length-(iWidth-ec));
            return pn(flags,arg,rs);
          }
        rs = pn(flags,arg,rs);
        if(rs.length<iWidth)
          { if(flags.indexOf('-')<0) rs = pad(rs,' ',rs.length-iWidth);
            else rs = pad(rs,' ',iWidth - rs.length);
          }    
        return rs;
      }
    var converters = new Array();
    converters['c'] = function(flags,width,precision,arg)
      { if(typeof(arg) == 'number') return String.fromCharCode(arg);
        if(typeof(arg) == 'string') return arg.charAt(0);
        return '';
      }
    converters['d'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,arg); 
      }
    converters['u'] = function(flags,width,precision,arg)
      { return converters['i'](flags,width,precision,Math.abs(arg)); 
      }
    converters['i'] =  function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = ((Math.abs(arg)).toString().split('.'))[0];
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        return processFlags(flags,width,rs,arg); 
      }
    converters['E'] = function(flags,width,precision,arg) 
      { return (converters['e'](flags,width,precision,arg)).toUpperCase();
      }
    converters['e'] =  function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toExponential(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs.replace(/^(.*)(e.*)$/,'$1.$2');
        return processFlags(flags,width,rs,arg);        
      }
    converters['f'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        if(isNaN(iPrecision)) iPrecision = 6;
        rs = (Math.abs(arg)).toFixed(iPrecision);
        if(rs.indexOf('.')<0 && flags.indexOf('#')>=0) rs = rs + '.';
        return processFlags(flags,width,rs,arg);
      }
    converters['G'] = function(flags,width,precision,arg)
      { return (converters['g'](flags,width,precision,arg)).toUpperCase();
      }
    converters['g'] = function(flags,width,precision,arg)
      { iPrecision = parseInt(precision);
        absArg = Math.abs(arg);
        rse = absArg.toExponential();
        rsf = absArg.toFixed(6);
        if(!isNaN(iPrecision))
          { rsep = absArg.toExponential(iPrecision);
            rse = rsep.length < rse.length ? rsep : rse;
            rsfp = absArg.toFixed(iPrecision);
            rsf = rsfp.length < rsf.length ? rsfp : rsf;
          }
        if(rse.indexOf('.')<0 && flags.indexOf('#')>=0) rse = rse.replace(/^(.*)(e.*)$/,'$1.$2');
        if(rsf.indexOf('.')<0 && flags.indexOf('#')>=0) rsf = rsf + '.';
        rs = rse.length<rsf.length ? rse : rsf;
        return processFlags(flags,width,rs,arg);        
      }  
    converters['o'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = Math.round(Math.abs(arg)).toString(8);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['X'] = function(flags,width,precision,arg)
      { return (converters['x'](flags,width,precision,arg)).toUpperCase();
      }
    converters['x'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        arg = Math.abs(arg);
        var rs = Math.round(arg).toString(16);
        if(rs.length<iPrecision) rs=pad(rs,' ',iPrecision - rs.length);
        if(flags.indexOf('#')>=0) rs='0x'+rs;
        return processFlags(flags,width,rs,arg); 
      }
    converters['s'] = function(flags,width,precision,arg)
      { var iPrecision=parseInt(precision);
        var rs = arg;
        if(rs.length > iPrecision) rs = rs.substring(0,iPrecision);
        return processFlags(flags,width,rs,0);
      }
    farr = fstring.split('%');
    retstr = farr[0];
    fpRE = /^([-+ #]*)(\d*)\.?(\d*)([cdieEfFgGosuxX])(.*)$/;
    for(var i=1; i<farr.length; i++)
      { fps=fpRE.exec(farr[i]);
        if(!fps) continue;
        if(arguments[i]!=null) retstr+=converters[fps[4]](fps[1],fps[2],fps[3],arguments[i]);
        retstr += fps[5];
      }
    return retstr;
  }
