$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});


$().ready(function(){
	function get_time_zone_offset() {
		var current_date = new Date( );
		var gmt_offset = current_date.getTimezoneOffset( ) / 60;
		return gmt_offset;
	}
	Set_Cookie( 'user_tz', get_time_zone_offset(), '', '/', '', '' );


	jQuery.fn.center = function () {
		this.css("position","absolute");
		this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
		return this;
	}
	//$(document).ajaxStop($.unblockUI);
	
	
	$('#feedback_message').center();
	

	$(window).scroll(function()
	{
		 $('#feedback_message').animate({top:$(window).scrollTop()+"px" },{queue: false, duration: 350});
	});
	
	$('#close_message').click(function()
	{
	  //the messagebox gets scrool down with top property and gets hidden with zero opacity
	   $("#feedback_message").fadeOut("slow");
	});

	$.ajaxSetup({
		timeout: 30000,
		cache: false,
		error:function(x,e){
			var err_reported = false;
			try{
				if(x.status==0){
					alert('You are offline!!\n Please Check Your Network.');
					err_reported = true;
				}else if(x.status==404){
					alert('Requested URL not found.');
					err_reported = true;
				}else if(x.status==500){
					alert('Internel Server Error.');
					err_reported = true;
				}
			}
			catch(err){}

			if(!err_reported){
				if(e=='parsererror'){
				alert('Error.\nParsing JSON Request failed.');
				}else if(e=='timeout'){
				alert('Request Time out please try again.');
				}else {
				alert('Unknow Error.\n'+x.responseText);
				}
			}
			setTimeout($.unblockUI); 
		}
	});
});


	
	function show_feedback(error_message, other_message){
			//clear_feedback()
			$('#feedback_message').bgiframe();
			show_msg = 0;
			if(!is_empty(error_message)){
				err_msg = "Följande fel inträffade:\n"+error_message;				
				$("#error_message").append(lf2br(err_msg));
				show_msg = 1;
			}
			if(!is_empty(other_message)){
				other_msg = other_message;				
				$("#other_message").append(lf2br(other_msg));
				show_msg = 1;
			}
			if(show_msg){
				$("#feedback_message").fadeIn("slow");							
				//$("#feedback_message").effect("shake", { times:2, direction:'down'}, 300);

				//$("#feedback_message").animate({
				 // top: "0px"
				 //}, 10 ).fadeOut(500).fadeIn(500);
			}
	}
	
	function clear_feedback(){
			$("#other_message").html('');
			$("#error_message").html('');
			$("#feedback_message").fadeOut("slow");
	}
	
	function ajax_get(url, load_to, loading_msg, frm_data_qs, callback_on_complete){
	    var frm_data_qs = typeof(frm_data_qs) != 'undefined' ? frm_data_qs : '';
	    var callback_on_complete = typeof(callback_on_complete) != 'undefined' ? callback_on_complete : '';
		if(frm_data_qs){
			url = url + '?' + frm_data_qs;
		}

		if(loading_msg){
			$.blockUI({ message: loading_msg });
		}
		$.get(url, {
			cache: false,
			is_ajax_call: "1"
		},
		function(response){
			//alert(response);
			var rsp_obj = parseJson(response);
			//alert(rsp_obj.html_content);
			var x = rsp_obj.html_content
			//alert(x.substr(x.length - 10));
			var unb = true;
			if(is_empty(rsp_obj.error_message)){
				unb = false;
				if(!is_empty(load_to)){
					$("#"+load_to).html(rsp_obj.html_content);	
				}
				if(callback_on_complete){
					callback_on_complete(rsp_obj);
				}else{
					setTimeout($.unblockUI); 
				}
			}
			if(unb){
				setTimeout($.unblockUI);
			}
			return false;
		}
		);
		return false;		
	}

	function ajax_post(url, load_to, loading_msg, frm_data_qs, callback_on_complete){
	    frm_data_qs = typeof(frm_data_qs) != 'undefined' ? frm_data_qs : '';
	    callback_on_complete = typeof(callback_on_complete) != 'undefined' ? callback_on_complete : '';
		if(loading_msg){
			$.blockUI({ message: loading_msg });
		}
		$.post(url, {
			cache: false,
			is_ajax_call: "1",
			frm_data_qs: frm_data_qs
		},
		function(response){
			//alert(response);
			var rsp_obj = parseJson(response);
			var unb = true;
			if(is_empty(rsp_obj.error_message)){
				unb = false;
				if(!is_empty(load_to)){
					$("#"+load_to).html(rsp_obj.html_content);	
				}
				if(callback_on_complete){
					callback_on_complete(rsp_obj);
				}else{
					setTimeout($.unblockUI); 
				}
			}
			if(unb){
				setTimeout($.unblockUI);
			}
			return false;
		}

		);
		return false;		
	}



	function parseJson(response){
//	alert(response);
		clear_feedback();
		var rsp_obj;
		rsp_obj = "";
		try{
			rsp_obj = jQuery.evalJSON(response);
			if(rsp_obj.request_completed != "~OK~"){
			  rsp_obj.error_message = "Oväntat svar\n"+response;
			  rsp_obj = "";
			  show_feedback("Oväntat svar\n"+response,'' );
			  $.unblockUI;
			}else{
				show_feedback(rsp_obj.error_message,rsp_obj.other_message );
				if(rsp_obj.page_redirect && !rsp_obj.error_message){
					show_feedback('', "Omdirigera " + rsp_obj.page_redirect + "...");
					$(location).attr('href',rsp_obj.page_redirect);
				}
			}
		}
		catch(err)
		{
		  alert(err);
		  rsp_obj = "";	
		  show_feedback("Oväntat svar\n"+response,'' );
		  $.unblockUI;
		}
		return rsp_obj; 
	}
    
   function setup_tooltip(){
   //$('.tooltip a').each(function()
   $("span[id^=tooltip]  a").each(function()
   {
      $(this).qtip(
      {
      position: {
         corner: {
            target: $(this).attr("c_target"),
            tooltip: $(this).attr("c_tooltip")
         }
      },
	  text: false,
      content: $(this).attr("tooltip"),
      style: {
         name: 'cream',
         padding: '7px 13px',
         width: {
            max: 210,
            min: 0
         },
         tip: true
      }
      });
	  });
	}

function ForceLength(objField, nLength, strWarning)
{
	var strField = new String(objField.value);

	if (strField.length > nLength) {
		alert(strWarning);
		objField.focus();
		return false;
	} else
		return true;
}


function ForceEntry(objField, strWarning)
{
	var strField = new String(objField.value);
	
	if (trim(strField) == "") {
		alert(strWarning);
		objField.select();
		return false;
	}
	return true;
}

// This function determines if the string passed in is a valid
// US zip code.  It accepts either ##### or #####-####.  If the
// string is valid, it returns true, else false.

function isZipcode(strZip)
{
	var s = new String(strZip);

	if (s.length != 5 && s.length != 10)
		// inappropriate length
		return false;


	for (var i=0; i < s.length; i++)
		if ((s.charAt(i) < '0' || s.charAt(s) > '9') && s.charAt(i) != '-')
			return false;

	return true;
}

function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function openWindow(url,window_name,winWidth,winHeight,fscroll,resize) {
	sWidth = screen.availWidth;
	sHeight = screen.availHeight;
	
	sLeft = (sWidth - winWidth) / 2;
	sTop = (sHeight - winHeight) / 2;
	if(fscroll == '') {fscroll = 0}
	if(resize == '') {resize = 'no'}
	
	rem = window.open(url,window_name,"width=" + winWidth + ",height=" + winHeight + ",top=" + sTop + ",left=" + sLeft + ",toolbar=0,menubar=0,status=0,scrollbars=" + fscroll + ",resizable="+resize);
	if (window.focus) {rem.focus()}
}


function DtDiff(date1, date2) {
   dte1 = new Date(Date.parse(date1));
   dte2 = new Date(Date.parse(date2));

    if (isNaN (dte1) || isNaN (dte2) ) {
        alert("Invalid date parameters") ;
        return null ;
    }


   diff = Math.abs(dte1.getTime() - dte2.getTime());

	days = 0;
	hours = 0;
	minutes = 0;
	seconds = 0;
  if((diff % 86400000) > 0)
   {
       rest = (diff % 86400000);
       days = (diff - rest) / 86400000;
       
       if((rest % 3600000) > 0 )
       {
           rest1 = (rest % 3600000);
           hours = (rest - rest1) / 3600000;
     

           if((rest1 % 60000) > 0 )
           {
               rest2 = (rest1 % 60000);
               minutes = (rest1 - rest2) / 60000;
               seconds = rest2/1000;
           }else{
               minutes = rest1 / 60000;
		   }
      }else{
           hours = rest / 3600000;
	   }
   }else{
       days = diff / 86400000;
	}

	var retarray = new Array(4);
	retarray[0]= days;
	retarray[1]= hours;
	retarray[2]= minutes;
	retarray[3]= seconds;
	return retarray;
}

function isAlphabetic(val) {
	
	if (val.match(/^[a-zA-Z]+$/)) {
		return true;
	}
	else {
		return false;
	}	
}

// check to see if input is alphanumeric
function isAlphaNumeric(val) {
	
	if (val.match(/^[a-zA-Z0-9]+$/)) {
		return true;
	}
	else {
		return false;
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function refreshParent() {
  window.opener.location.href = window.opener.location.href;

  if (window.opener.progressWindow)
		
 {
    window.opener.progressWindow.close()
  }
  window.close();
}

// Base64 code from Tyler Akins -- http://rumkin.com - Start
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}
// Base64 code from Tyler Akins -- http://rumkin.com - End

function encode64_urlsafe(input){
	output = encode64(input);
	output.replace( '+', '-');
	output.replace( '/', '_');
	output.replace( '=', '');
	return output;
}



function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}



function Set_Cookie( name, value, expires, path, domain, secure)
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}


function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + '=' +
			( ( path ) ? ';path=' + path : '') +
			( ( domain ) ? ';domain=' + domain : '' ) +
			';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

function numval(input){
  retval = 0;
  if(IsNumeric(input)){
	retval = parseFloat(input);		
  }
  return retval;
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

   if(sText.length == 0){
   	  IsNumber = false;
   }
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}


function isInteger(s){
	var i;
	if(isNaN(s)) return false;
	if(s == "") return false;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}


function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function d_val(dtStr, dtFormat){
	var dtCh = '/';
	var err = "";
	var dtFormat = (typeof(dtFormat) != 'undefined')?dtFormat : 'dd/mm/yyyy';

	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)

	if(dtFormat == 'dd/mm/yyyy'){
		var strDay=dtStr.substring(0,pos1)
		var strMonth=dtStr.substring(pos1+1,pos2)
		var strYear=dtStr.substring(pos2+1)
	}else if(dtFormat == 'mm/dd/yyyy'){
		var strDay=dtStr.substring(pos1+1,pos2)
		var strMonth=dtStr.substring(0,pos1)
		var strYear=dtStr.substring(pos2+1)
	}else{
		err = "Unrecognized date format";	
	}

	if(!err){
		strYr=strYear
		if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
		if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
		for (var i = 1; i <= 3; i++) {
			if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
		}
		month=parseInt(strMonth)
		day=parseInt(strDay)
		year=parseInt(strYr)
		var err = "";
		if (pos1==-1 || pos2==-1){
			 err = "The date format should be : dd/mm/yyyy";
		}
		if (strMonth.length<1 || month<1 || month>12){
			 err = "Please enter a valid month";
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			 err = "Please enter a valid day";
		}
		if (strYear.length != 4 || year==0 ){
			 err = "Please enter a valid 4 digit year";
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			 err = "Please enter a valid date";
		}
	}
	return  err;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//when working with file and directory paths - start
//var fullpath = 'C:\\Test\\Test.txt';
//var filename = Path.GetFileName(fullpath);

var Path = {
    ChangeExtension:function(path,extension)
    {
        var regExp = /([a-zA-Z]{1,})$/;
        var matches = regExp.exec(path);
        return path.replace(regExp,extension);
    },
    GetDirectoryName:function(path)
    {
        var regExp = /^[\\]?[:]?([^:\\]*)/;
        var matches = regExp.exec(path);
        return matches[1];
    },
    GetExtension:function(path)
    {
        var regExp = /.([a-zA-Z]{1,})$/;
        var matches = regExp.exec(path);
        return matches[0];
    },
    GetFileName:function(path)
    {
        var regExp = /([^\\]{1,}.[a-zA-Z]{1,})$/;
        var matches = regExp.exec(path);
        return matches[0];
    },
    GetFileNameWithoutExtension:function(path)
    {
        var regExp = /([^.\\]{1,}).[a-zA-Z]{1,}$/;
        var matches = regExp.exec(path);
        return matches[0];
    }
}
//when working with file and directory paths - End



//var foo = 'Snuggleuffagus';                                                         
//alert(foo.shorten(3, '&raquo;'));
String.prototype.shorten = function(n, i) {                                         
    var indicator = i || '…';                                                       
    return (this.length > n) ? String(this.substr(0, n)+indicator) : String(this);  
};                                                                                  
                                                                                    

//Array functions - Start
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

// -- Standard functions

// Array.concat() - Join two arrays
if( typeof Array.prototype.concat==='undefined' ) {
 Array.prototype.concat = function( a ) {
  for( var i = 0, b = this.copy(); i<a.length; i++ ) {
   b[b.length] = a[i];
  }
  return b;
  };
}

// Array.copy() - Copy an array
if( typeof Array.prototype.copy==='undefined' ) {
 Array.prototype.copy = function() {
  var a = [], i = this.length;
  while( i-- ) {
   a[i] = typeof this[i].copy!=='undefined' ? this[i].copy() : this[i];
  }
  return a;
 };
}

// Array.pop() - Remove and return the last element of an array
if( typeof Array.prototype.pop==='undefined' ) {
 Array.prototype.pop = function() {
  var b = this[this.length-1];
  this.length--;
  return b;
 };
}

// Array.push() - Add an element to the end of an array, return the new length
if( typeof Array.prototype.push==='undefined' ) {
 Array.prototype.push = function() {
  for( var i = 0, b = this.length, a = arguments, l = a.length; i<l; i++ ) {
   this[b+i] = a[i];
  }
  return this.length;
 };
}

// Array.shift() - Remove and return the first element
if( typeof Array.prototype.shift==='undefined' ) {
 Array.prototype.shift = function() {
  for( var i = 0, b = this[0], l = this.length-1; i<l; i++ ) {
   this[i] = this[i+1];
  }
  this.length--;
  return b;
 };
}

// Array.slice() - Copy and return several elements
if( typeof Array.prototype.slice==='undefined' ) {
 Array.prototype.slice = function( a, c ) {
  var i, l = this.length, r = [];
  if( !c ) { c = l; }
  if( c<0 ) { c = l + c; }
  if( a<0 ) { a = l - a; }
  if( c<a ) { i = a; a = c; c = i; }
  for( i = 0; i < c - a; i++ ) { r[i] = this[a+i]; }
  return r;
 };
}

// Array.splice() - Remove or replace several elements and return any deleted elements
if( typeof Array.prototype.splice==='undefined' ) {
 Array.prototype.splice = function( a, c ) {
  var i = 0, e = arguments, d = this.copy(), f = a, l = this.length;
  if( !c ) { c = l - a; }
  for( i; i < e.length - 2; i++ ) { this[a + i] = e[i + 2]; }
  for( a; a < l - c; a++ ) { this[a + e.length - 2] = d[a - c]; }
  this.length -= c - e.length + 2;
  return d.slice( f, f + c );
 };
}

// Array.unshift() - Add an element to the beginning of an array
if( typeof Array.prototype.unshift==='undefined' ) {
 Array.prototype.unshift = function() {
  this.reverse();
  var a = arguments, i = a.length;
  while(i--) { this.push(a[i]); }
  this.reverse();
  return this.length;
 };
}

// -- 4umi additional functions

// Array.forEach( function ) - Apply a function to each element
Array.prototype.forEach = function( f ) {
 var i = this.length, j, l = this.length;
 for( i=0; i<l; i++ ) { if( ( j = this[i] ) ) { f( j ); } }
};

// Array.indexOf( value, begin, strict ) - Return index of the first element that matches value
Array.prototype.indexOf = function( v, b, s ) {
 for( var i = +b || 0, l = this.length; i < l; i++ ) {
  if( this[i]===v || s && this[i]==v ) { return i; }
 }
 return -1;
};

// Array.insert( index, value ) - Insert value at index, without overwriting existing keys
Array.prototype.insert = function( i, v ) {
 if( i>=0 ) {
  var a = this.slice(), b = a.splice( i );
  a[i] = v;
  return a.concat( b );
 }
};

// Array.lastIndexOf( value, begin, strict ) - Return index of the last element that matches value
Array.prototype.lastIndexOf = function( v, b, s ) {
 b = +b || 0;
 var i = this.length; while(i-->b) {
  if( this[i]===v || s && this[i]==v ) { return i; }
 }
 return -1;
};

// Array.random( range ) - Return a random element, optionally up to or from range
Array.prototype.random = function( r ) {
 var i = 0, l = this.length;
 if( !r ) { r = this.length; }
 else if( r > 0 ) { r = r % l; }
 else { i = r; r = l + r % l; }
 return this[ Math.floor( r * Math.random() - i ) ];
};

// Array.shuffle( deep ) - Randomly interchange elements
Array.prototype.shuffle = function( b ) {
 var i = this.length, j, t;
 while( i ) {
  j = Math.floor( ( i-- ) * Math.random() );
  t = b && typeof this[i].shuffle!=='undefined' ? this[i].shuffle() : this[i];
  this[i] = this[j];
  this[j] = t;
 }
 return this;
};

// Array.unique( strict ) - Remove duplicate values
Array.prototype.unique = function( b ) {
 var a = [], i, l = this.length;
 for( i=0; i<l; i++ ) {
  if( a.indexOf( this[i], 0, b ) < 0 ) { a.push( this[i] ); }
 }
 return a;
};

// Array.walk() - Change each value according to a callback function
Array.prototype.walk = function( f ) {
 var a = [], i = this.length;
 while(i--) { a.push( f( this[i] ) ); }
 return a.reverse();
};

//Array functions - End


function JSClock() {
   var time = new Date()
   var hour = time.getHours()
   var minute = time.getMinutes()
   var second = time.getSeconds()
   var temp = "" + ((hour > 12) ? hour - 12 : hour)
   if (hour == 0)
      temp = "12";
   temp += ((minute < 10) ? ":0" : ":") + minute
   temp += ((second < 10) ? ":0" : ":") + second
   temp += (hour >= 12) ? " P.M." : " A.M."
   return temp
} 

function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}

function pop_win(n, u, w, h) {
  str = "width="+w+",height="+h+",resizable=1,status=0,scrollbars=1";
  rem = window.open(u, n, str);
  if (window.focus) {rem.focus()}
  if(rem != null) {
    if(rem.opener == null)
      rem.opener = self;
  }
}

function popwin(theURL,winName,features) { //v2.0
	leftVal = Math.abs((screen.width - 800) / 2);
	topVal = Math.abs((screen.height - 500) / 2);
	features = features+',left='+leftVal+',top='+topVal
	rem = window.open(theURL,winName,features);
	if (window.focus) {rem.focus()}
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function hide_it(id){
		document.getElementById(id).style.visibility = 'hidden'; 
		document.getElementById(id).style.display = 'none'; 	
}

function show_it(id){
		document.getElementById(id).style.visibility = 'visible'; 
		document.getElementById(id).style.display = 'block'; 
}

function get_file_extension(filename) {
	ext = filename.replace(/^.*?\.([a-zA-Z0-9]+)$/, "$1");
	if(ext != ""){
		ext = '.'+ext;
	}
	return ext;
}


function len(strInput)
{
      return strInput.length;
}

function lf2br(strInput){
	return (strInput.replace(/(\n)/g, "<br/>"));
}
function limitChars(textid, limit, infodiv)
{ 
    infodiv = typeof(infodiv) != 'undefined' ? infodiv : '';
	var text = $('#'+textid).val(); 
	var textlength = text.length; 
	if(textlength > limit) 
	{ 
		$('#'+textid).val(text.substr(0,limit)); 
		return false; 
	}else {
	  if(infodiv != ''){
	  	$('#' + infodiv).html((textlength) +'/' + limit + '(Max)'); 
	  }
	  return true; 
	} 
}

//IMPORTANAT:The passing variable to 'is_set' function should be ALREADY DECLARED otherwise this will show error
function is_set( variable){
	return( typeof( variable ) != 'undefined' );
}

//IMPORTANAT:The passing variable to 'is_empty' function should be ALREADY DECLARED otherwise this will show error
function is_empty(variable){
	return (!is_set(variable) || trim(variable) == "");
}

function strpos (haystack, needle, offset) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Onno Marsman    
    // +   bugfixed by: Daniel Esteban
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14

    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

function get_qs(addr, key){
	var qs = "";
	var key = '/'+key+'-';
	if (strpos(addr,key) === 0)
	{
		qs = addr.substring((key.length));
	}
	return qs
}

function getParameterByName(name, qs)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec('?'+qs);
  //alert(qs);
  if( results == null )
    return "";
  else
    return results[1];
}

function addslashes(str) {
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\0/g,'\\0');
return str;
}

function stripslashes(str) {
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\0/g,'\0');
str=str.replace(/\\\\/g,'\\');
return str;
}

