// common.js - Common javascript functions for performing various tasks.
// Example: <script type="text/javascript" src="javascripts/tools/common.js"></ script>


// LimitText - Will limit and update the total number of characters allowed.
// Example: <input name="uploadfrom" id="uploadfrom" type="text" onkeydown="LimitText(this.form.uploadfrom,'uploadfromcount',100);" onkeyup="LimitText(this.form.uploadfrom,'uploadfromcount',100);" maxlength="100"  class="formstyle1"/><span id="uploadfromcount">100</span>

function LimitText(limitField, limitCount, limitNum) 
{
	if (limitField.value.length > limitNum) 
	{
		limitField.value = limitField.value.substring(0, limitNum);
	} 
	else 
	{
		document.getElementById(limitCount).innerHTML=limitNum - limitField.value.length;
	}
}

// GetUrl - Will get the contents of any url using Ajax, the result is given to you by a call to a function you specify.
// Example: GetUrl("www.abc.com", MyFinishedFunction);
//			function MyFinishedFunction(result) // result equals whatever was returned by the url specified
var GetUrlFinished;

function GetUrl(url,finishfunction)
{
	GetUrlFinished=finishfunction;
	
	try 
	{
		xmlhttp=window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
	} 
	catch (e) 
	{
	}
	xmlhttp.onreadystatechange=GetUrlAnswer;
	xmlhttp.open("GET", url);
	xmlhttp.send(null);	
}

function GetUrlPost(url,finishfunction,key1,value1)
{
	GetUrlFinished=finishfunction;
	
	parameters=key1+"="+encodeURI(value1);
	//if (key2!="") parameters+="&"+key2+"="+encodeURI(value2);
	//if (key3!="") parameters+="&"+key3+"="+encodeURI(value3);	
	
	try 
	{
		xmlhttp=false;
		if (window.XMLHttpRequest)
		{
			xmlhttp=new XMLHttpRequest();
			if (xmlhttp.overrideMimeType) xmlhttp.overrideMimeType("text/html");
		}
		else
		{
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	} 
	catch (e) 
	{
	}
	xmlhttp.onreadystatechange=GetUrlAnswer;
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.setRequestHeader("Content-length", parameters.length);
	xmlhttp.setRequestHeader("Connection", "close");
	xmlhttp.send(parameters);		
}

function GetUrlAnswer()
{
	if ((xmlhttp.readyState==4)&&(xmlhttp.status==200)) 
	{
		GetUrlFinished(xmlhttp.responseText);
	}
}

// SubmitForm - Will submit a form.
function SubmitForm(id)
{
	document.getElementById(id).submit();
}

// SetHTML - Will change the HTML using the id of a block of HTML.
// Example: SetHTML("myid","Polo");
//          <span id="myid">Marco</span> // Marco will be changed to Polo when the example is executed.
function SetHTML(id,html)
{
	document.getElementById(id).innerHTML=html;
}

function GetHTML(id)
{
	return(document.getElementById(id).innerHTML);
}

// SetValue - Will change the value of an item, such as form fields.
function SetValue(id,value)
{
	document.getElementById(id).value=value;
}

function GetValue(id)
{
   return(document.getElementById(id).value);
}

function GetCheck(id)
{
	if (document.getElementById(id).checked==true) return(1);
	return(0);
}

function SetCheck(id,value)
{
	if (value) document.getElementById(id).checked=true;
	else document.getElementById(id).checked=false;
}

function ToggleCheck(id)
{
	if (!GetCheck(id)) document.getElementById(id).checked=true;
	else document.getElementById(id).checked=false;
}

function GetClass(id)
{
	return(document.getElementById(id).className);	
}

function SetClass(id,value)
{
	document.getElementById(id).className=value;
}

function GetObject(id)
{
   return(document.getElementById(id));
}

// ShowRows - Will show a range of rows in a table, if count is set to 1, all the rows are shown.  Set show to 0 to hide the rows.
function ShowRows(tableid, rowstart, count, show)
{
	var stl;
	if (show) stl = 'block'
	else stl = 'none';
	
	var tbl  = document.getElementById(tableid);
	var rows = tbl.getElementsByTagName('tr');
	
	if (count==0) 
	{
		count=rows.length;
	}
	
	for (i=0;i<count;i++)
	{
		rows[rowstart+i].style.display=stl;
	}
}

// ShowColumns - Will show a range of columns in a table, if count is set to 0, all the columns are shown.  Set show to 0 to hide the columns.
function ShowColumns(tableid, columnstart, count, show)
{
	var stl;
	if (show) stl = 'block'
	else stl = 'none';
	
	var tbl  = document.getElementById(tableid);
	var rows = tbl.getElementsByTagName('tr');
	
	for (var row=0; row<rows.length;row++) 
	{
		var cels=rows[row].getElementsByTagName('td')
		if (count==0) count=cels.length;
	
		for (i=0;i<count;i++) cels[columnstart+i].style.display=stl;
	}
}

// GetCSSRule - Will get a CSS rule object, and allow you to change it.
//              For more information visit http://www.hunlock.com/blogs/Totally_Pwn_CSS_with_Javascript
// Example: GetCSSRule(".style1").style.display="none";

function GetCSSRule(ruleName, deleteFlag) 
{
	ruleName=ruleName.toLowerCase();
	if (document.styleSheets) {
	for (var i=0; i<document.styleSheets.length; i++) {
	var styleSheet=document.styleSheets[i];
	var ii=0;
	var cssRule=false;
	do {
	if (styleSheet.cssRules) {
	cssRule = styleSheet.cssRules[ii];
	} else {
	cssRule = styleSheet.rules[ii];
	}
	if (cssRule) {
	if (cssRule.selectorText.toLowerCase()==ruleName) {
	if (deleteFlag=='delete') {
	if (styleSheet.cssRules) {
	styleSheet.deleteRule(ii);
	} else {
	styleSheet.removeRule(ii);
	}
	return true;
	} else {
	return cssRule;
	}
	}
	}
	ii++;
	} while (cssRule)
	}
	}
	return false;
}

// KillCSSRule - Will delete a CSS rule.
function KillCSSRule(ruleName) 
{
	return GetCSSRule(ruleName,'delete');
}

// AddCSSRule - Will add a CSS rule.
function AddCSSRule(ruleName) 
{
	if (document.styleSheets) {
	if (!GetCSSRule(ruleName)) {
	if (document.styleSheets[0].addRule) {
	document.styleSheets[0].addRule(ruleName, null,0);
	} else {
	document.styleSheets[0].insertRule(ruleName+' { }', 0);
	}
	}
	}
	return GetCSSRule(ruleName);
} 

// ShowItem
function ShowItem(id,show)
{
	if (show) stl = 'block'
	else stl = 'none';
	
	document.getElementById(id).style.display=stl;
}


// StartHidden - Will create a class that will be hidden when you start.  To use, you must set the items class to use the classname you specify.
// Example: StartHidden("hideclass");
//			<span id="myid" class="hideclass">
//			ShowItem("myid",1); // Call ShowItem to show it again later.
function StartHidden(classname)
{
	AddCSSRule("."+classname).style.display="none";
}

function LoadPage(url)
{
	window.location.href=url;
}

function PopPage(url,parameters)
{
	// parameters="scrollbars=no,menubar=no,top=0,left=0,height=100,width=100,resizable=no,toolbar=no,location=no,status=no";
	window.open(url,"",parameters);
}

function ReloadPage()
{
	window.location.reload();
}

//function CopyToClipboard(text2copy) 
//{
//    var flashcopier = 'flashcopier';
//    
//	if (!document.getElementById(flashcopier))
//	{
//      var divholder = document.createElement('div');
//      divholder.id = flashcopier;
//      document.body.appendChild(divholder);
//    }
//    document.getElementById(flashcopier).innerHTML = '';
//    
//	var divinfo = '<embed src="javascripts/clipboard/clipboard.swf" FlashVars="clipboard='+escape(text2copy)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
//    
//	document.getElementById(flashcopier).innerHTML = divinfo;
//}

function CopyToClipboard(text)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", text);
	}
	else
	{
    var flashId = 'flashId-HKxmj5';

    /* Replace this with your clipboard.swf location */
    var clipboardSWF = 'javascripts/clipboard/_clipboard.swf';

    if(!document.getElementById(flashId)) {
        var div = document.createElement('div');
        div.id = flashId;
        document.body.appendChild(div);
    }
    document.getElementById(flashId).innerHTML = '';
    var content = '<embed src="' + 
        clipboardSWF +
        '" FlashVars="clipboard=' + encodeURIComponent(text) +
        '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashId).innerHTML = content;
	}
}

// SetCookie - Will set a cookie.  Expires is in minutes.
function SetCookie( name, value, expires, path, domain, secure ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	if (expires)
	{
		expires = expires * 1000 * 60;
	}
	
	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 GetCookie( check_name ) {
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false;
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		a_temp_cookie = a_all_cookies[i].split( '=' );
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function DeleteCookie(name, path, domain) {
  var theValue = GetCookie(name); 
  if (theValue) {
      document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'');
	  }
}

function SelectDropDownItem(listid, value)
{
	for (iLoop = 0; iLoop< document.getElementById(listid).options.length; iLoop++)
	{    
		if (document.getElementById(listid).options[iLoop].value.toLowerCase() == value.toLowerCase())
		{
			document.getElementById(listid).options[iLoop].selected = true;
			break;
		}
	}	
}

function GetCaretPosition(el)
{
	var iCaretPos = 0;
	
	if (document.selection) // IE hack
	{
		if (el.type == 'text') // textbox
		{
			var selectionRange = document.selection.createRange();
			selectionRange.moveStart ('word', -el.value.length);
			iCaretPos = selectionRange.text.length;
		}
		else // textarea
		{
			iCaretPos = Math.abs(document.selection.createRange().moveStart("character", -1000000)) - 193;
		}
	}
	else if (el.selectionStart || el.selectionStart == '0') // Firefox
	{
		iCaretPos = el.selectionStart;
	}
	
	return iCaretPos;
}

function SetCaretPosition (el, iCaretPos)
{
	if (document.selection) // IE
	{
		var range;
		
		range = document.selection.createRange();
		
		if (el.type == 'text') // textbox
		{
			range.moveStart ('character', -el.value.length);
			range.moveEnd ('character', -el.value.length);
			range.moveStart ('character', iCaretPos);
			range.select();
		}
		else // textarea
		{
			range.collapse(false);
			range.move ('character', iCaretPos - el.value.length + el.value.substring(iCaretPos).split('\n').length - 1);
			range.select();
		}
	}
	//else if (el.selectionStart || el.selectionStart == '0') // Firefox
	//{
	//	el.setSelectionRange(iCaretPos, iCaretPos);
	//}
}

function GetStringInbetween(target,string1,string2,start)
{
	var result=[];
	s1=target.indexOf(string1,start)+string1.length+1;
	s2=target.indexOf(string2,start+(string1.length)+1);
	if ((s1==-1)||(s2==-1)) 
	{
		result[0]="";
		result[1]=-1;
	}
	else
	{
		result[0]=target.substring(s1,s2);
		result[1]=s2+string2.length;
	}
	return(result);
}

var TextFaderTitles=new Array();
var TextFaderTimes=new Array();	

function TextFaderRotate(id,s1,s2,s3,d1,d2,d3,speed)
{
	TextFaderRotateEngine(0,id,s1,s2,s3,d1,d2,d3,speed);
}

function TextFaderRotateEngine(index,id,s1,s2,s3,d1,d2,d3,speed)
{
	var lasttime;

	GetObject(id).style.color="rgb("+parseInt(s1)+","+parseInt(s2)+","+parseInt(s3)+")";
	SetHTML(id,TextFaderTitles[index]);
	TextFader(id,s1,s2,s3,d1,d2,d3,speed);
	lasttime=TextFaderTimes[index];
	
	index++;
	if (index==TextFaderTitles.length) index=0;
	
	setTimeout("TextFaderRotateEngine("+index+",'"+id+"',"+s1+","+s2+","+s3+","+d1+","+d2+","+d3+","+speed+")",lasttime);
}	

function TextFader(id,s1,s2,s3,d1,d2,d3,speed)
{
	GetObject(id).style.color="rgb("+parseInt(d1)+","+parseInt(d2)+","+parseInt(d3)+")";
	TextFaderEngine(id,GetHTML(id),s1,s2,s3,d1,d2,d3,0,0,speed);
}

function TextFaderEngine(id,text,s1,s2,s3,d1,d2,d3,index1,index2,speed)
{
	var output,target;
	var fadestep=34;
	var fadetop=100;
	var x1,x2,x3;
	var h1,h2,h3;
	
	if (index2==0)
	{
		output=text.substr(0,index1);
		target="<span id=\"textfader\" style=\"color:#"+GetHexColor(s1,s2,s3)+";\">"+text.substr(index1,1)+"</span>";
		SetHTML(id,output+target);
	}
		
	x1=s1+((d1-s1)*(index2/fadetop));
	x2=s2+((d2-s2)*(index2/fadetop));
	x3=s3+((d3-s3)*(index2/fadetop));				
	
	index2+=fadestep;
	
	GetObject("textfader").style.color="rgb("+parseInt(x1)+","+parseInt(x2)+","+parseInt(x3)+")";
	
	if (index2>fadetop) 
	{
		index2=0;
		index1++;
	}

	if (index1<=text.length)
	{
		setTimeout("TextFaderEngine('"+id+"','"+text+"',"+s1+","+s2+","+s3+","+d1+","+d2+","+d3+","+index1+","+index2+","+speed+")",speed);
	}
}

function GetHexColor(r,g,b)
{
	h1=GetHex(parseInt(r));
	if (h1.length<2) {h1="0"+h1;}
	h2=GetHex(parseInt(g));
	if (h2.length<2) {h2="0"+h2;}
	h3=GetHex(parseInt(b));
	if (h3.length<2) {h3="0"+h3;}
	
	return(h1+h2+h3);
}

function GetHex(d) 
{
	var hD="0123456789ABCDEF";
	var h=hD.substr(d&15,1);
	
	while (d>15) 
	{
		d>>=4;
		h=hD.substr(d&15,1)+h;
	}
	
	return h;
}