// JavaScript Document
// dependant on jquery.js

var dataType=[];
dataType['integer']			= /^(0|[1-9]+[0-9]*)$/;
dataType['positive_integer']= /^([1-9]+[0-9]*)$/;

dataType['float']			= /^((\.)|(\.[0-9]*)|(0\.?)|(0\.[0-9]*)|([1-9]+[0-9]*\.?)|([1-9]+[0-9]*\.[0-9]*))$/;		
dataType['number']			= /^\d+$/;

dataType['currency2']		= /^((\.)|(\.[0-9]{0,2})|(0\.?)|(0\.[0-9]{0,2})|([1-9]+[0-9]*\.?)|([1-9]+[0-9]*\.[0-9]{0,2}))$/;
dataType['currency5']		= /^((\.)|(\.[0-9]{0,5})|(0\.?)|(0\.[0-9]{0,5})|([1-9]+[0-9]*\.?)|([1-9]+[0-9]*\.[0-9]{0,5}))$/;

dataType['phone']			= /^[0-9]{6,15}$/;		
dataType['common']			= /^[A-Za-z0-9_]+$/;

dataType['email']			= /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;	



function empty(str){
	 
    return $.trim(str) == '';
}

//innerttrim :: replace multiple spaces with a single space
function innerTrim(str)
{
	return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}


function weekday2Date(weekdayNumber, format){
	if(!format || typeof format == "undefined")
		 format = "M d, l";
		 
	var wd_arr = array('Su ', 'Mo ', 'Tu ', 'We ', 'Th ', 'Fr ', 'Sa ');
	var sunday = mktime(0, 0, 0, parseInt(date('m')), parseInt(date('d'))+(0-parseInt(date('w'))), parseInt(date('Y')));	
	var weekdayNumber = parseInt(weekdayNumber);
	//assuming week starts from sunday (01)
	weekdayNumber--;
	
	return date(format, sunday+weekdayNumber*60*60*24);
	/*for ($n=0; $n<7; $n++) {			
		echo $wd_arr[$n], date('Y-m-d', $sunday+$n*60*60*24), "<br/>\n";
	}*/
}

//capitalize the first character of each word in the string
function ucwords(str){
	
	if(!empty(str)){
		splitted = str.split(' ');
		space = result = '';
		for(i=0; i<splitted.length; i++){
			s = splitted[i]	;
			
				if(s.length == 1)
					result += space+s.substring(0, 1).toUpperCase();
				else
					result += space+s.substring(0, 1).toUpperCase()+s.substring(1, s.length);
				space = ' ';
				
		}
		return ltrim(result);
	}
}

	


function isemail(str){
	
	str = $.trim(str);
	if(str.length){
		return dataType['email'].test(str);
	}
}

//http://www.bloggingdeveloper.com?author=bloggingdeveloper 
//var author_value = getQuerystring('author'); 
function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
} 



function redirect(url){
	
	document.location = url;
}


function isDate(date_value) {
    var mo, day, yr;
   
    var re = /\b\d{1,2}[\/-]\d{1,2}[\/-]\d{4}\b/;
    if (re.test(date_value)) {
        var delimChar = (date_value.indexOf("/") != -1) ? "/" : "-";
        var delim1 = date_value.indexOf(delimChar);
        var delim2 = date_value.lastIndexOf(delimChar);
        mo = parseInt(date_value.substring(0, delim1), 10);
        day = parseInt(date_value.substring(delim1+1, delim2), 10);
        yr = parseInt(date_value.substring(delim2+1), 10);
        var testDate = new Date(yr, mo-1, day);
        //alert(testDate)
        if (testDate.getDate() == day) {
            if (testDate.getMonth() + 1 == mo) {
                if (testDate.getFullYear() == yr) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
    return false;
}



//especially used to make javascripts in the response of an ajax request executable. otherwise the scripts wont be executable

function evalScript(scripts)
{	try
	{	if(scripts != '')	
		{	var script = "";
			scripts = scripts.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
									 if (scripts !== null) script += arguments[1] + '\n';
										return '';});
			if(script) (window.execScript) ? window.execScript(script) : window.setTimeout(script, 0);
		}
		return false;
	}
	catch(e)
	{	//alert(e)
	}
}

//validate multiple email addresses separated by semi-colon
function validateMultiEmail(email){
	
	var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*$/;
	regex = new RegExp(pattern);
        
	email = trim(email);
	email = rtrim(email, ';');

	return regex.test(email);
	
}

	
function isWebUrl(url){
		
	var pattern= /^http:\/\/[A-Za-z0-9\.-]{3,}(\.[A-Za-z]{1,3}(.[A-Za-z]{2, 3})?)$/
	if (url.match(pattern))
	{		
		return true;
	}
	else
	{
		return false; 
	}
}

function isPhone(str){
	var bracket_flag=-1;
	for(i = 0; i < str.length; i++){
		mychar = str.charAt(i);
		if((mychar >= "0" && mychar <= "9") || mychar == "-" || mychar == "+" || mychar == "(" || mychar == ")")
		{
			if(mychar == "+" && i!=0)			return false;
			if(mychar == "-" && i==0)			return false;
			if(mychar == ")" && i<2)			return false;
			if(mychar == "(")					bracket_flag=0;
			if(mychar == ")")
				if(bracket_flag==0)				bracket_flag=1;
				else							return false;
			
		} 
		else
			return false; 
	}
	
	return true;
}

function checkEnter(e){ //e is event object passed from function invocation

	
	var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : e.which  ? e.which : 0; 
	
	return key == 13 ? true : false; //if generated character code is equal to ascii 13 (if enter key)			

}



//=========================================================================================================================
// FCKEditor API functions

//Extracted From:: ckeditor/_source/core/editor.js

//--------updateElement()
/**
 * Updates the <textarea>; element that has been replaced by the editor with
 * the current data available in the editor.
 * @example
 * CKEDITOR.instances.editor1.updateElement();
 * alert( document.getElementById( 'editor1' ).value );  // The current editor data.
 */
 
 
 //--------insertElement()
/**
 * Inserts an element into the currently selected position in the
 * editor.
 * @param {CKEDITOR.dom.element} element The element to be inserted
 *		into the editor.
 * @example
 * var element = CKEDITOR.dom.element.createFromHtml( '&lt;img src="hello.png" border="0" title="Hello" /&gt;' );
 * CKEDITOR.instances.editor1.<b>insertElement( element )</b>;
 */

//--------insertHtml()
/**
 * Inserts HTML into the currently selected position in the editor.
 * @param {String} data HTML code to be inserted into the editor.
 * @example
 * CKEDITOR.instances.editor1.<b>insertHtml( '&lt;p&gt;This is a new paragraph.&lt;/p&gt;' )</b>;
 */

//--------setData()
/**
 * Sets the editor data. The data must be provided in raw format.
 * @param {String} data HTML code to replace the curent content in the editor.
 * @param {Function} callback Function to be called after the setData is completed.
 * @example
 * CKEDITOR.instances.editor1.setData( '&lt;p&gt;This is the editor data.&lt;/p&gt;' );
 * CKEDITOR.instances.editor1.setData( '&lt;p&gt;Some other editor data.&lt;/p&gt;', function()
 * {
 * 		CKEDITOR.instances.editor1.checkDirty(); 	// true
 * } );
 */

//--------getData()
/**
 * Gets the editor data. The data will be in raw format. It is the same
 * data that is posted by the editor.
 * @type String
 * @returns (String) The editor data.
 * @example
 * if ( CKEDITOR.instances.editor1.getData() == '' )
 *     alert( 'There is no data available' );
 */

//--------execCommand()
/**
 * Executes a command.
 * @param {String} commandName The indentifier name of the command.
 * @param {Object} [data] Data to be passed to the command
 * @returns {Boolean} "true" if the command has been successfuly
 *		executed, otherwise "false".
 * @example
 * editorInstance.execCommand( 'Bold' );
 */

//--------destroy()
/**
 * Destroys the editor instance, releasing all resources used by it.
 * If the editor replaced an element, the element will be recovered.
 * @param {Boolean} [noUpdate] If the instance is replacing a DOM
 *		element, this parameter indicates whether or not to update the
 *		element with the instance contents.
 * @example
 * alert( CKEDITOR.instances.editor1 );  e.g "object"
 * CKEDITOR.instances.editor1.destroy();
 * alert( CKEDITOR.instances.editor1 );  "undefined"
 */

//--------addCss()
/**
* Add a trunk of css text to the editor which will be applied to the wysiwyg editing document.
* Note: This function should be called before editor is loaded to take effect.
* @param css {String} CSS text.
* @example
* editorInstance.addCss( 'body { background-color: grey; }' );
*/
 
//--------addCommand()
 /**
 * Adds a command definition to the editor instance. Commands added with
 * this function can be later executed with {@link #execCommand}.
 * @param {String} commandName The indentifier name of the command.
 * @param {CKEDITOR.commandDefinition} commandDefinition The command definition.
 * @example
 * editorInstance.addCommand( 'sample',
 * {
 *     exec : function( editor )
 *     {
 *         alert( 'Executing a command for the editor name "' + editor.name + '"!' );
 *     }
 * });
*/
 

//=========================================================================================================================



// returns the number of occurences of srchStr in mainStr

function countInstances(mainStr, srchStr) 
{
	var charCount = 0;
	var offset = 0;
	do {
		offset = mainStr.indexOf(srchStr, offset);
		charCount += (offset != -1) ? 1 : 0;
	} while (offset++ != -1)
	return charCount
}


function cleanQString(qs, filter){
		
	if(qs){
		switch(filter){
			case 'range' : 	qs = qs.replace(/&?range\=[a-z0-9]-[a-z0-9]/g, ''); break;
			case '_pg' : 	qs = qs.replace(/&?_pg\=\d+/g, '');
		}
		return qs;
	}
	else return '';
}

//calculates the no of days between two given dates::result could be negative as well
function days_between(date1, date2) {
    
	date1_splited = date1.toString().split('-');
	date2_splited = date2.toString().split('-');
	date1 = new Date(date1_splited[0], date1_splited[1], date1_splited[2]);
	date2 = new Date(date2_splited[0], date2_splited[1], date2_splited[2]);
	
	var DSTAdjust = 0;
    // constants used for our calculations below
    oneMinute = 1000 * 60;
    var oneDay = oneMinute * 60 * 24;
    // equalize times in case date objects have them
    date1.setHours(0);
    date1.setMinutes(0);
    date1.setSeconds(0);
    date2.setHours(0);
    date2.setMinutes(0);
    date2.setSeconds(0);
    // take care of spans across Daylight Saving Time changes
    if (date2 > date1) {
        DSTAdjust = (date2.getTimezoneOffset( ) - date1.getTimezoneOffset( )) * oneMinute;
    } else {
        DSTAdjust = (date1.getTimezoneOffset( ) - date2.getTimezoneOffset( )) * oneMinute;    
    }
    var diff = date2.getTime( ) - date1.getTime( ) - DSTAdjust;
    return Math.ceil(diff/oneDay);
}


//parameters must be provided in 24 hours time format : 12:54:00
function timeDifference(laterdate,earlierdate, returnOption) {
	
	if(typeof returnOption == "undefined" || returnOption == null ){
		var returnOption = 	'T';
	}
	//console.log(laterdate+' '+earlierdate);
	var returnDiff = returnShortDiff = '';
	
	var arrLaterDate = laterdate.split(' ');
	var arrEarlierDate = earlierdate.split(' ');
	
	var srtLaterTime = arrLaterDate[1];
	var srtLaterDate = arrLaterDate[0];
	
	var srtEarlierTime = arrEarlierDate[1];
	var srtEarlierDate = arrEarlierDate[0];
	
	var arrLaterDate = srtLaterDate.split('-');
	var arrEarlierDate = srtEarlierDate.split('-');
	
	var arrLaterTime = srtLaterTime.split(':');
	var arrEarlierTime = srtEarlierTime.split(':');
	
	
	
	var laterdate = new Date(arrLaterDate[0],arrLaterDate[1],arrLaterDate[2], arrLaterTime[0], arrLaterTime[1], 0);  
	var earlierdate = new Date(arrEarlierDate[0],arrEarlierDate[1],arrEarlierDate[2], arrEarlierTime[0], arrEarlierTime[1], 0);
	
	
	
    var difference = laterdate.getTime() - earlierdate.getTime();
 
    var daysDifference = Math.floor(difference/1000/60/60/24);
    difference -= daysDifference*1000*60*60*24
 
    var hoursDifference = Math.floor(difference/1000/60/60);
    difference -= hoursDifference*1000*60*60
 
    var minutesDifference = Math.floor(difference/1000/60);
    difference -= minutesDifference*1000*60
 
    var secondsDifference = Math.floor(difference/1000);
	
	if(hoursDifference.length == 1)
		hoursDifference = '0'+hoursDifference.toString();
	if(minutesDifference.length == 1)
		minutesDifference = '0'+minutesDifference.toString();
	
 	if(parseInt(hoursDifference) > 1){
		returnDiff += hoursDifference + ' Hours ';
		returnShortDiff += hoursDifference + ' Hrs. ';
	}
	else{
		returnDiff += hoursDifference + ' Hour ';
		returnShortDiff += hoursDifference + ' Hr. ';
	}
	
	if(parseInt(minutesDifference) > 1){
		returnDiff += minutesDifference + ' Minutes ';
		returnShortDiff += minutesDifference + ' Mins. ';
	}
	else{
		returnDiff += minutesDifference + ' Minute ';
		returnShortDiff += minutesDifference + ' Min. ';
	}
	
	switch(returnOption){
		
		case 'S': return returnDiff; break;	 //X Hours Y Minutes
		case 'L': return returnShortDiff; break;	 //X Hrs. Y Mins.
		case 'T': return hoursDifference+":"+minutesDifference; break;	//X:Y
		case 'D': return parseFloat(hoursDifference+"."+minutesDifference); break; //X.Y
		default: return '';
	}
	//alert(timeDifference('20:50','18:50'));	
}




function preloadImages(arrImageUrl){

	if(arrImageUrl && arrImageUrl.length){
		for(i in arrImageUrl){
			
			imgLoader = new Image();// preload image
			imgLoader.src = arrImageUrl[i];
		}
	}
}
/*arr  = new Array('http://localhost/eticket/apanel/themes/admin/alt-bg-button.gif');
preloadImages(arr );*/


//check the corresponding checkbox when the delete icon is clicked and uncheck all others :: users
function check4deletion(obj){
	$('.check-all').attr('checked', false);
	obj.parent().parent().parent().find("input[type='checkbox']").attr('checked', false);   
	obj.parent().parent().find(':checkbox').attr('checked', true);

}
//=========================================================================================================================
// FCKEditor API functions





function removeEditor()
{
	if ( !editor )
		return;

	// Retrieve the editor contents. In an Ajax application, this data would be
	// sent to the server or used in any other way.
	document.getElementById( 'editorcontents' ).innerHTML = editor.getData();
	document.getElementById( 'contents' ).style.display = '';

	// Destroy the editor.
	editor.destroy();
	editor = null;
}



function InsertHTML()
{
	// Get the editor instance that we want to interact with.
	var oEditor = CKEDITOR.instances.editor1 ;
	var value = document.getElementById( 'plainArea' ).value ;

	// Check the active editing mode.
	if (oEditor.mode == 'wysiwyg' )
	{
		// Insert the desired HTML.
		oEditor.insertHtml( value ) ;
	}
	else
		alert( 'You must be on WYSIWYG mode!' ) ;
}

function setContents(instance, value)
{
	// Get the editor instance that we want to interact with.
	var oEditor = eval('CKEDITOR.instances.'+instance) ;
	
	// Set the editor contents (replace the actual one).
	oEditor.setData( value ) ;
}

function getContents(instance)
{
	// Get the editor instance that we want to interact with.
	var oEditor = eval('CKEDITOR.instances.'+instance) ;

	// Get the editor contents
	return oEditor.getData();
}

function ExecuteCommand( commandName )
{
	// Get the editor instance that we want to interact with.
	var oEditor = CKEDITOR.instances.editor1 ;

	// Check the active editing mode.
	if (oEditor.mode == 'wysiwyg' )
	{
		// Execute the command.
		oEditor.execCommand( commandName ) ;
	}
	else
		alert( 'You must be on WYSIWYG mode!' ) ;
}


//=========================================================================================================================

//applying default texts to textbox
//the text from the input's title is applied
$(document).ready(function()
{
    $(".defaultText").focus(function(){
        if ($(this).val() == $(this)[0].title){
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    $(".defaultText").blur(function(){
        if ($(this).val() == ""){
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });
    
    $(".defaultText").blur();        
});


/*TOOLTIPS*/
function simple_tooltip(target_items, name){
 $(target_items).each(function(i){
							   
		if($.trim($(this).attr('title')) != ''){
			$("body").append("<div class='"+name+"' id='"+name+i+"'><p>"+$(this).attr('title')+"</p></div>");
			var my_tooltip = $("#"+name+i);
			
			$(this).removeAttr("title").mouseover(function(){
					my_tooltip.css({opacity:0.8, display:"none"}).fadeIn(400);
			}).mousemove(function(kmouse){
					my_tooltip.css({left:kmouse.pageX+15, top:kmouse.pageY+15});
			}).mouseout(function(){
					my_tooltip.fadeOut(400);				  
			});
		}
	});
}

/*
usage:
$(document).ready(function(){
	 simple_tooltip("a","tooltip");
});*/
