// ###### Check functions ####################################################################################
function trim(string)
{
    return string.replace(/(^\s+)|(\s+$)/g, "");
}

function checkUsername(usernameStr)
{
 var rex = new RegExp("^[A-Za-z0-9_-]{4,}$", "i");
    if(!rex.test(usernameStr))
    {
     return false;
    }
  return true;
}

function checkIsIntNumberCorrect(sNumber)
{
	var re = new RegExp("^(\\d)+$");
	var ares = re.exec(sNumber); 
	if ( null == ares )
	{
		return false;
	}

	return true;
}

function checkIsDoubleNumberCorrect(sNumber)
{
	var re = new RegExp("^-?(\\d)+(\\.(\\d)+)?$");
	var ares = re.exec(sNumber);
	if ( null == ares )
	{
		return false;
	}

	return true;
}

function checkIsUnsignedDoubleNumberCorrect(sNumber)
{
	var re = new RegExp("^(\\d)+(\\.(\\d)+)?$");
	var ares = re.exec(sNumber); 
	if ( null == ares )
	{
		return false;
	}

	return true;
}

function checkEmail(sEmail)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(sEmail)) {
		return true;
	}
	return false;
}

// Checks for the following valid date formats:
// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
// Also separates date into month, day, and year variables
function isValidDate(dateStr) {
    
    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

    // To require a 4 digit year entry, use this line instead:
    // var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

    var matchArray = dateStr.match(datePat); // is the format ok?
    if (matchArray == null) {
    //alert("Date is not in a valid format.")
    return false;
    }
    month = matchArray[1]; // parse date into variables
    day = matchArray[3];
    year = matchArray[4];
    if (month < 1 || month > 12) { // check month range
    //alert("Month must be between 1 and 12.");
    return false;
    }
    if (day < 1 || day > 31) {
    //alert("Day must be between 1 and 31.");
    return false;
    }
    if ((month==4 || month==6 || month==9 || month==11) && day==31) {
    //alert("Month "+month+" doesn't have 31 days!")
    return false
    }
    if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
    if (day>29 || (day==29 && !isleap)) {
    //alert("February " + year + " doesn't have " + day + " days!");
    return false;
       }
    }
return true;  // date is valid
}

// ###### Output text functions ###############################################################################

function priceFormat(value)
{
 	var ValueStr = new String( value );
	var ind = ValueStr.lastIndexOf(".");
	// xxxx.xx
	if ( ind >= 0 )
	{
		if ( ind == ValueStr.length - 2 )
		{
			ValueStr += "0";
		}
	
		if ( ind < ValueStr.length - 3 )
		{
			ValueStr = ValueStr.substr(0, ind + 3);
		}
	}
	else
	{
		ValueStr += ".00";
	}
	// xxxx.xx
	
	// x,xxx.xx
	ind = ValueStr.lastIndexOf(".");
	if ( ind >= 4 )
	{
		ValueStr = ValueStr.substr(0, ind - 3) + "," + ValueStr.substr(ind - 3, 6);
	}
	// x,xxx.xx
	return ValueStr;
}

// ###### Ajax syncronized functions ###############################################################################
var url_next_syncronized = '';

function loadurlSyncronized(url_first, url_next, obj_output) 
{
    var url_first = url_first.split('?');
    var url_next = url_next.split('?');
	$.ajax({
		type: "POST",
                url: url_first[0],
                data: url_first[1],
		dataType: "html",
                beforeSend: function()
   		{
                    $("#listing").fadeTo("fast", 0.33);
                },
               complete: function()
   		{
                    $("#listing").fadeTo("fast", 1);
                },
		success: function(data_first){ 
			$('#errorMessage').html(data_first);
			$.ajax({
				type: "POST",
                                url: url_next[0],
                                data: url_next[1],
				dataType: "html",
				complete: function(){},
				success: function(data_next){ 
					if (obj_output == null) obj_output = 'listing';
					$('#'+obj_output).html(data_next);
				},
				error: function()
				{
					//alert('Export operation failed!');
				}
			});
		},
		error: function()
		{
			//alert('Export operation failed!');
		}
	});
}

function loadurl(url, obj_output) 
{
	$.ajax({
		type: "POST",
		url: url,
		dataType: "html",
                beforeSend: function()
   		{
                    $("#listing").fadeTo("fast", 0.33);
                },
               complete: function()
   		{
                    $("#listing").fadeTo("fast", 1);
                },
		success: function(data){ 
			if (obj_output == null) obj_output = 'listing';
			$('#'+obj_output).html(data);
		},
		error: function()
		{
			//alert('Export operation failed!');
		}
	});
}

function loadurlListing(dest) 
{
	loadurl(dest);
}

function alertUrl(url) 
{
	$.ajax({
		type: "POST",
		url: url,
		dataType: "html",
		complete: function(){},
		success: function(data){ 
			if (data != '') alert(data);
		},
		error: function()
		{
			//alert('Export operation failed!');
		}
	});
}

// ###### Element view actions ###############################################################################
function loadURLElement(url, obj_output, data) 
{
	var data;
	if (null == data || undefined == data) data = {};	

	$.ajax({
		type: "POST",
		url: url,
		data : data,
		dataType: "html",
                beforeSend: function()
   		{
                    $("#"+obj_output).fadeTo("fast", 0.33);
                },
               complete: function()
   		{
                    $("#"+obj_output).fadeTo("fast", 1);
                },
		success: function(data){ 
			$('#'+obj_output).html(data);
		},
		error: function()
		{
			alert('Export operation failed!');
		}
	});

	$('#'+obj_output).css('display', 'block');
}  

function hideElement(obj_output)
{
//	$('#'+obj_output).fadeOut();
	$('#'+obj_output).css('display', 'none');
	$('#'+obj_output).html("");
}

// ###### Block popup functions ###############################################################################
function updatePopupWindow(url_new)
{
	$('#modalContent').css('display', 'none');
	$('#modalContent').html("");
	$('#modalPreloader').css('display', 'block');
	
	$.ajax({
			type: "POST",
			url: url_new,
		    dataType: "html",
			complete: function(){},
			success: function(data){ 
				$('#modalPreloader').css('display', 'none');
				$('#modalContent').css('display', 'block');
				$('#modalContent').html(data);
			},
			error: function()
			{
				//alert('Export operation failed!');
			}
		});
}

function getBodyScrollTop()
{
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
}

function popupWindow(nWidth, nHeight, url_show)
{
	updatePopupWindow(url_show);

	$('#modalContent').css('display', 'block');

	if (nWidth <= 0) nWidth = $(window).width();

	// show modal window
        $('#body').block({
        message: $('#modalWindow'),
     // disable vertical centering
        centerY: false,
        css:
        {
                            //top:  ($(window).height() - nHeight) /2 + 'px',
                            top: getBodyScrollTop() + 40,
                            left: ($(window).width() - nWidth) /2 + 'px',
                            width: nWidth + 'px',
                            heigth: nHeight + 'px'
                    }
    });
	 $(".blockOverlay").css('height',$(document).height());
}
function closePopup()
{
	$('#modalContent').html("");
	$('#body').unblock({ }); 

}

// ###### Confirm functions ###############################################################################
function confirm_state_change() 
{
	if (confirm('Are you sure you want to change checked items state?')) {
		return true;
	} else {
		return false;
	}
}

function confirm_delete() 
{
	if (confirm('Are you sure you want to remove?')) {
		return true;
	} else {
		return false;
	}
}

// ###### Other functions ###############################################################################
function _onmouseout (_scr, _Img) {
   eval ("document.images." + _Img + ".src = '" + _scr + "'" ) ;
}


function loadurlListingSyncronized(dest) {

    var data;
     	$.ajax({
		   type: "GET",
		   dataType: "html",
		   error: function(response){showMessage('error ' + response.status, 'Error while getting data...');},
		   url: dest,
		   data: data,
		   success: function(response)
               {
//                    hidePopup();
                    $("#listing").html(response);
               }
		});

}


function doSearch(bm, tab_id) {
    var bm, tab_id;
    var search = '';
    //if ($('#search').val())
        search = '&search=' + $('#search').val();
    //window.location.href='index.php?bm='+bm+'&a=10.00&tab_id='+tab_id+'&id=0&search=' + $('#search').val();
    window.location.href='index.php?bm='+$.getUrlVars('bm')+'&a=10.00&tab_id='+tab_id+'&id='+$.getUrlVars('id') + search;
    //loadurlListing('index.php?bm='+getUrlVars()['bm']+'&a=10.00'+tab_id+'&id='+getUrlVars()['id']+'&search=' + $('#search').val() );
}

function initTinyMCE(element)
{
       tinyMCE.init({
          mode : "exact",
          elements : element,
          theme : "advanced",
          theme_advanced_buttons1_add_before : "save,newdocument,separator, fontsizeselect",
          theme_advanced_buttons2_add_before: "cut,copy,paste,separator,forecolor,backcolor",
          theme_advanced_toolbar_location : "top",
          theme_advanced_toolbar_align : "left",
          theme_advanced_statusbar_location : "bottom",
          plugi2n_insertdate_dateFormat : "%Y-%m-%d",
          plugi2n_insertdate_timeFormat : "%H:%M:%S",
          file_browser_callback : "fileBrowserCallBack",
          paste_use_dialog : false,
          theme_advanced_resizing : false,
          theme_advanced_resize_horizontal : true,
          theme_advanced_link_targets : "_something=My somthing;_something2=My somthing2;_something3=My somthing3;",
          paste_auto_cleanup_on_paste : true,
          paste_convert_headers_to_strong : false,
          paste_strip_class_attributes : "all",
          paste_remove_spans : false,
          paste_remove_styles : false,
          relative_urls : false,
          remove_script_host : false,
          convert_urls : false          
     });
}

function initTinyMCE_full(element)
{
       tinyMCE.init({
          mode : "exact",
          elements : element,
          theme : "advanced",
          theme_advanced_buttons1_add_before : "save,newdocument,separator, fontsizeselect",
          theme_advanced_buttons2_add_before: "cut,copy,paste,separator,forecolor,backcolor",
          theme_advanced_buttons3_add_before : "ibrowser",
          theme_advanced_toolbar_location : "top",
          theme_advanced_toolbar_align : "left",
          theme_advanced_statusbar_location : "bottom",
          plugi2n_insertdate_dateFormat : "%Y-%m-%d",
          plugi2n_insertdate_timeFormat : "%H:%M:%S",
          //file_browser_callback : "fileBrowserCallBack",
          file_browser_callback : "tinyBrowser",
          paste_use_dialog : false,
          theme_advanced_resizing : false,
          theme_advanced_resize_horizontal : true,
          theme_advanced_link_targets : "_something=My somthing;_something2=My somthing2;_something3=My somthing3;",
          paste_auto_cleanup_on_paste : true,
          paste_convert_headers_to_strong : false,
          paste_strip_class_attributes : "all",
          paste_remove_spans : false,
          paste_remove_styles : false,
          relative_urls : false,
          remove_script_host : false,
          convert_urls : false          
          
         // Other options
         // relative_urls : false
     });
}



// Get object of URL parameters
//var allVars = $.getUrlVars();
// Getting URL var by its nam
//var byName = $.getUrlVar('name');
$.extend({
  getUrlVars: function(){
    var hash;
    var vars = new Object();
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

//Reload listing table
function reloadListing()
{
    var data = '';
    var params = $.getUrlVars();
    if (params.tab_id) params.a = '10.00' + params.tab_id;
    else params.a = '10.001';
    $.each(params, function(key, value) {
        data += '&' + key + '=' + value;
    });
    data = data.substr(1);
    loadURLElement('index.php', 'listing', data);

}


function blockStandart(element) {
    var element;
    $("#"+element).block({
                        message: '',
                        css: {
                                backgroundColor: '#fff',
                                color: '#000',
                                top:'1%',
                                left:'1%',
                                width:'100px'
                        },
                        overlayCSS:  {
                            backgroundColor: '#fff',
                            opacity:         0.6
                        },
                        centerY: false,
                        centerX: false
                });
}

/*
 * Tooltip
 */
function showTooltip(id)
{
    var id;
    var content = $("#preview_"+id).attr('content');

    $('<div class="tooltip">' + content + '</div>').appendTo("#preview_"+id).fadeIn('fast');




//NOT WORKING IN IE(
//    $(this).bind('mousemove', function(e){
//            $('div.tooltip').css({
//                    'top': e.pageY - ($('div.tooltip').height() / 2) - 5,
//                    'left': e.pageX + 15
//            });
//    });

//    $(this).bind('mouseleave', function(e){
//        hideTooltip();
//    });
}

function hideTooltip()
{
    $('div.tooltip').remove();
}


(function($){
 $.fn.extend({

 	customStyle : function(options) {
          var classStyle = 'customStyle';
          if (options) classStyle = options;

	  if(!$.browser.msie || ($.browser.msie&&$.browser.version>6)){
	  return this.each(function() {

                var currentSelected = $(this).find(':selected');
                $(this).after('<span class="'+classStyle+'SelectBox"><span class="'+classStyle+'SelectBoxInner">'+currentSelected.text()+'</span></span>').css({position:'absolute', opacity:0,fontSize:$(this).next().css('font-size')});
                var selectBoxSpan = $(this).next();
                var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) -parseInt(selectBoxSpan.css('padding-right'));
                var selectBoxSpanInner = selectBoxSpan.find(':first-child');
                selectBoxSpan.css({display:'inline-block'});
                selectBoxSpanInner.css({width:selectBoxWidth, display:'inline-block'});
                var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));
                $(this).height(selectBoxHeight).change(function(){
                        // selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
                selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
                });

	  });
	  }
	}
 });
})(jQuery);

//json
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);





