﻿/// *************************************************///
///                rsh ///
/// *************************************************///
function historyChange(newLocation, historyData) {
	var historyMsg = (typeof historyData == "object" && historyData != null
		? historyStorage.toJSON(historyData)
		: historyData
	);
	var msg = "<b>A history change has occured:</b> | newLocation=" + newLocation + " | historyData=" + historyMsg + " |";
	log(msg);
	
	if(historyData !== null){
		hash = historyData.hash;
		formName = historyData.formName;
		destinationDIV = historyData.destinationDIV;
		remote_url = historyData.remote_url;
		animationTarget = historyData.animationTarget;
		Mactive_ID = historyData.Mactive_ID;
		queryString = historyData.queryString;

		if(historyData !== null && formName !== 'form-filter'){        
		 	call_ajax(hash, formName, destinationDIV, remote_url, animationTarget, Mactive_ID, queryString);
		}
	}
};

addHistoryEvent = function(newLocation, historyData) {
	dhtmlHistory.add(newLocation, historyData);
	if (typeof historyData == "object") {/*stringify this so we can log it better*/
		historyData = historyStorage.toJSON(historyData);
	}
	var msg = "<b>A history event has been added:</b> [newLocation=" + newLocation + " | historyData=" + historyData + "]";
	log(msg);
	
	qs = historyData;
	if(historyData !== null){
		//loadAjaxHistory(qs);
	}
}
//'', 'form_n2', 'content-holder', 'home.php', 'progress_search'
function call_ajaxx(docForm) {
	queryString = formData2QueryString(hash, docForm, content_holder, process_page, progress_animation);
	rand = 'Query' + Math.random();
	addHistoryEvent(rand, queryString);
}

function formData2QueryString(docForm) {
	var strSubmit       = '';
	var formElem;
	var strLastElemName = '';
	
	for (i = 0; i < docForm.elements.length; i++) {
		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text, select, hidden, password, textarea elements
			case 'text':
			case 'select-one':
			case 'hidden':
			case 'password':
			case 'textarea':
					strSubmit += formElem.name + 
					'=' + escape(formElem.value) + '&'
			break;
		}
	}
	return strSubmit;
}

// debugging //
function log(msg) {
	var logNode = document.getElementById("logWin");
	var content = "<p>" + msg + "</p>" + logNode.innerHTML;
	logNode.innerHTML = content;
}
function clearLog(msg) {
	var logNode = document.getElementById("logWin");
	logNode.innerHTML = "";
}
function viewObjectState() {
	log("<b>Dumping dhtmlHistory object state</b>");
	for (var key in dhtmlHistory) {
		var val = dhtmlHistory[key];
		if (typeof val !== 'function' && (typeof val !== 'object' || val === null)) {
			log("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + key + "</b>: " + dhtmlHistory[key]);
		}
	}
	log("<b>Done dumping dhtmlHistory object state</b>");
	log("<b>Dumping historyStorage object state</b>");
	for (var key in historyStorage) {
		var val = historyStorage[key];
		if (typeof val != 'function' && typeof val != 'object') {
			log("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + key + "</b>: " + historyStorage[key]);
		}
	}
	log("<b>Done dumping historyStorage object state</b>");
}



/* GENERAL AJAX FUNCTIONS */

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {      
		xmlhttp = new XMLHttpRequest();    
	} else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   
	} 

function getNewHTTPObject()
{
    var xmlhttp;
	
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
    {
        try
        {
            xmlhttp = new XMLHttpRequest();
        }
        catch (e)
        {
            xmlhttp = false;
        }
    } else if (window.ActiveXObject) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");   
	}

    return xmlhttp;
}
function anon_refresh(page, target){
	// push a refresh by page and target div 
	var xmlhttp_anon;
	var mystring = '&sled_make=';
	xmlhttp_anon = getNewHTTPObject();
	xmlhttp_anon.open("POST", page, true);
	xmlhttp_anon.onreadystatechange=function() {
		if (xmlhttp_anon.readyState==4) {

			if ( xmlhttp_anon.responseText == "" ) {

			} else {
				ajaxResponse = xmlhttp_anon.responseText;
				document.getElementById(target).innerHTML = ajaxResponse;
				document.getElementById('progress_search').innerHTML = '';
			}					   

		}
	}
	xmlhttp_anon.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp_anon.send(mystring);
}

function show_form(id){
	// hide all forms
	document.getElementById('cat_sleds').style.display = 'none';
	document.getElementById('cat_gear').style.display = 'none';
	document.getElementById('cat_classifieds').style.display = 'none';
	document.getElementById('cat_parts').style.display = 'none';
	// make form visible
	document.getElementById('cat_' + id.value).style.display ='inline';
	// ajax search call
	call_ajax('', 'cat_' + id.value, 'result-div', 'result.php', 'progress_search', '', '', true);
}

function show_form_anon(id){
	// hide all forms
	document.getElementById('cat_sleds').style.display = 'none';
	document.getElementById('cat_gear').style.display = 'none';
	document.getElementById('cat_classifieds').style.display = 'none';
	document.getElementById('cat_parts').style.display = 'none';
	// make form visible
	document.getElementById('cat_' + id).style.display ='inline';
	// ajax search call
	call_ajax('', 'cat_' + id, 'result-div', 'result.php', 'progress_search', '', '', true);
}

function show_form_dealer(cat, id){
	anon_refresh_dealer('buy.php', 'main-content-middle', cat, id);
}

function anon_refresh_dealer(page, target, cat, id){
	// push a refresh by page and target div 
	var xmlhttp_anon;
	var mystring = '&sled_make=';
	xmlhttp_anon = getNewHTTPObject();
	xmlhttp_anon.open("POST", page, true);
	xmlhttp_anon.onreadystatechange=function() {
		if (xmlhttp_anon.readyState==4) {

			if ( xmlhttp_anon.responseText == "" ) {

			} else {
				ajaxResponse = xmlhttp_anon.responseText;
				document.getElementById(target).innerHTML = ajaxResponse;
				document.getElementById('progress_search').innerHTML = '';
				document.getElementById('cat_' + cat).style.display ='inline';
				var h = 0;
				switch(cat){
					case 'sleds' :
						h = 0;
						break;
					case 'gear' :
						h = 1;
						break;
					case 'classifieds' :
						h = 2;
						break;
					case 'parts' :
						h = 3;
						break;
					default :
						h = 0;
						cat = 'sleds';
				}
				document.cat_select.s_cat[h].checked = true;
				var hash = new Array('seller_id', id, 'cat', cat);
				call_ajax(hash, 'cat_' + cat, 'result-div', 'result.php', 'progress_search', '', '', true);
			}					   

		}
	}
	xmlhttp_anon.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp_anon.send(mystring);
}

function updateModels(target){
	var xmlhttp2;
	var mystring = '&sled_make=' + target;
	xmlhttp2 = getNewHTTPObject();
	xmlhttp2.open("POST", 'inc/modelsDrop.php', true);
	xmlhttp2.onreadystatechange=function() {
		if (xmlhttp2.readyState==4) {

			if ( xmlhttp2.responseText == "" ) {

			} else {
				ajaxResponse = xmlhttp2.responseText;
				document.getElementById('modelsDrop').innerHTML = ajaxResponse;
				document.getElementById('progress_search').innerHTML = ''; // clear animation
			}					   

		}
	}
	xmlhttp2.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp2.send(mystring);
}
function updateCounties(target){
	var xmlhttp3;
	var mystring = '&state=' + target;
	xmlhttp3 = getNewHTTPObject();
	xmlhttp3.open("POST", 'inc/countiesDrop.php', true);
	xmlhttp3.onreadystatechange=function() {
		if (xmlhttp3.readyState==4) {

			if ( xmlhttp3.responseText == "" ) {

			} else {
				ajaxResponse = xmlhttp3.responseText;
				document.getElementById('conditions_county_div').innerHTML = ajaxResponse;
				document.getElementById('progress_search').innerHTML = ''; // clear animation
			}					   

		}
	}
	xmlhttp3.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp3.send(mystring);
}

/* GENERAL LOGIN/LOGOUT FUNCITONS */
function updateLoginBox(){ // not used, just ajax into the admin panel
	var xmlhttp3;
	var mystring = '&sled_make=';
	xmlhttp3 = getNewHTTPObject();
	xmlhttp3.open("POST", 'logout.php', true);
	xmlhttp3.onreadystatechange=function() {
		if (xmlhttp3.readyState==4) {

			if ( xmlhttp3.responseText == "" ) {

			} else {
				ajaxResponse = xmlhttp3.responseText;
				document.getElementById('login_box').innerHTML = ajaxResponse;
				document.getElementById('progress_search').innerHTML = ''; // clear animation
			}					   

		}
	}
	xmlhttp3.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xmlhttp3.send(mystring);
}

/* GENERAL SELL FUNCITONS */

function show_form_sell(id){
	// hide all forms
	document.getElementById('cat_sleds').style.display = 'none';
	document.getElementById('cat_gear').style.display = 'none';
	document.getElementById('cat_classifieds').style.display = 'none';
	document.getElementById('cat_parts').style.display = 'none';
	// make form visible
	document.getElementById('cat_' + id.value).style.display ='inline';
	call_ajax('', 'cat_' + id.value, 'result-div', 'sell/sell_result.php', 'progress_search', '', '', true);
}

function show_form_sell_dealer(id){
	// hide all forms
	document.getElementById('cat_sleds').style.display = 'none';
	document.getElementById('cat_gear').style.display = 'none';
	document.getElementById('cat_classifieds').style.display = 'none';
	document.getElementById('cat_parts').style.display = 'none';
	// make form visible
	document.getElementById('cat_' + id.value).style.display ='inline';
	call_ajax('', 'cat_' + id.value, 'result-div', 'admin/sell/sell_result.php', 'progress_search', '', '', true);
}

function openImagesWindow(inID, cat){
	var picsWindow = window.open("sell/images.php?id=" + inID + "&cat=" + cat, '', 'resizable,width=680px,height=740px');
}

function openImagesWindowDealer(inID){
	var picsWindow = window.open("admin/dealer_images/images.php?id=" + inID, '', 'scrollbars,resizable,width=730px,height=740px');
}


var step = 10;
var animSpeed = 200;

/// not used right now, later?
var cachedRecords = new Array();
var cachedDetailImages = new Array();
var cdi = new Array();
imageArray = new Array();

function resetcache(){
	for(var i = 0;i < cachedRecords.length;i++){
		cachedRecords[i] = '';	
	}
}
/// *************************************************///
///                nav-box item functions ///
/// *************************************************///

function show(id, scrollH){
    tbl = document.getElementById(id);
    t = parseInt(tbl.style.height);
    imgNode = document.getElementById(tbl.id + "-pic");
    imgNode.src = "images_common/nav_open_26_22.jpg";
	
	scrollH + 20; // acoomodate ie 6 scroll performance
    t1 = new Tween(document.getElementById(id).style,'height',Tween.strongEaseOut,30,scrollH,.5,'px');
    t1.start();
    // swap image, need to name image id the same as the div id plus "-pic"
    
    
}
function hide(id, scrollH){
    tbl = document.getElementById(id);
    t = parseInt(tbl.style.height);
    imgNode = document.getElementById(tbl.id + "-pic");
    imgNode.src = "images_common/nav_closed_26_22.jpg";
    t1 = new Tween(document.getElementById(id).style,'height',Tween.strongEaseOut,t,30,.5,'px');
    t1.start();    
}
function hideAllNav(evt){
	// close all nav divs, used when we call a non-result page
	var allTags = new Array();
	allTags = document.getElementsByTagName("div");
	for(i=0;i<allTags.length;i++){
		if(allTags[i].className=="nav-box" && allTags[i].id != 'nav-pref' 
				&& allTags[i].scrollHeight != 30){ // never close pref div 
			var Cid = allTags[i].id;
			scrollH = allTags[i].scrollHeight;
			hide(Cid, scrollH);
		}
	}
}
function showHideNav(id){
    tbl = document.getElementById(id.parentNode.parentNode.id); // changed this to refelct position in form
    scrollH = document.getElementById(id.parentNode.parentNode.id).scrollHeight; // total height of element
    var nId = tbl.id;
    
    if(tbl.id != 'nav-pref'){ // only close tags if we're not passing in the pref div
        // close all other divs first
        var allTags = new Array();
        allTags = document.getElementsByTagName("div");
        for(i=0;i<allTags.length;i++){
            if(allTags[i].className=="nav-box" && allTags[i].id != nId && allTags[i].id != 'nav-pref' 
                    && allTags[i].scrollHeight != 30){ // never close pref div 
                var Cid = allTags[i].id;
                scrollH = allTags[i].scrollHeight;
                hide(Cid, scrollH);
            }
        }
    }
    tbl = document.getElementById(id.parentNode.parentNode.id);
    scrollH = document.getElementById(id.parentNode.parentNode.id).scrollHeight; // total height of element
    var nId = tbl.id;
	var ajax_call_id = id.parentNode.id;
    
    if(parseInt(tbl.style.height) <= 30){
        show(nId, scrollH);
		if(ajax_call_id != 'pref'){ // only do if it's a regular search ::TAKE AWAY when we create a sp for search preferences, or remove it entierly
			call_ajax('', ajax_call_id, 'content-holder', 'result.php', 'progress_search', '', '', true);
		}
        return;
    }
    hide(nId, scrollH);
    
}


/// ***********************************************?*///
///               table functions ///
/// *************************************************///

var rHeight = 82;
var user_duration = .8;

function showTbl(id, scrollH, mid){
    tbl = document.getElementById(id);
    t = parseInt(tbl.style.height);
    //scrollH + 30; // we add this to accomodate the thumbnail images
    t1 = new Tween(document.getElementById(id).style,'height',Tween.strongEaseOut,rHeight,scrollH,user_duration,'px'); // (element, prop, tween, start, end, time, unit)
	t2 = new OpacityTween(document.getElementById('bottom_' + mid),Tween.strongEaseOut,0,100,user_duration); // (element, prop, start opacity, end opacity, duration)
    t1.start(); 
	t2.start();
}
function hideTbl(id, scrollH, mid){
    tbl = document.getElementById(id);
    t = parseInt(tbl.style.height);
    
    t1 = new Tween(document.getElementById(id).style,'height',Tween.strongEaseOut,t,rHeight,user_duration,'px');
	t2 = new OpacityTween(document.getElementById('bottom_' + mid),Tween.strongEaseOut,100,0,user_duration);
    t1.start();
	t2.start();
}

var oid = null; // need to set a function pointer to pass data, thanks ms
function expandTbl(id, bid, mid){ // top id, bottom id, and mactive id
	oid = id;
	imgNode = document.getElementById(bid);
	
	imgNode.parentNode.parentNode.innerHTML = "<a href=\"javascript:void(null);\" onclick=\"collapseTbl('" + id + "' , '" + bid + "' , '" + mid + "');\"><img id=\"" + bid + "\" src=\"images_common/results_paging/closeRecord.jpg\" alt=\"\" class=\"expand-button\" border=\"0\" height=\"22\" width=\"79\"></a>";

	//setTimeout(showHideTblReal, 500, id); moz way
	var tripped = false;
	for(var i = 0; i < cachedRecords.length; i++){
		if(cachedRecords[i] == oid && document.getElementById(oid).scrollHeight > 130){ // must be same id AND have a scroll height to proves it was loaded
			showHideTblReal(oid, mid);
			tripped = true;
		}
	}
	if(!tripped){
		cachedRecords.push(id);
		showHideTblReal(id, mid); // ms, moz way, 500 milli-s seems to be enough -- UPDATE, not needed with new event model, DONE
								  // push id of div, plus itterator for opacity fading, used in showTbl and hideTbl
	}	
}
function collapseTbl(id, bid, mid){
	oid = id;
	imgNode = document.getElementById(bid);
	
	imgNode.parentNode.parentNode.innerHTML = "<a href=\"javascript:void(null);\" onclick=\"expandTbl('" + id + "' , '" + bid + "' , '" + mid + "');\"><img id=\"" + bid + "\" src=\"images_common/results_paging/expandRecord.jpg\" alt=\"\" class=\"expand-button\" border=\"0\" height=\"22\" width=\"79\"></a>";

	// cached results
	for(var i = 0; i < cachedRecords.length; i++){
		if(cachedRecords[i] == oid){
			showHideTblReal(oid, mid);
		}
	}
	//setTimeout(showHideTblReal, 500); // ms, moz way, 500 milli-s seems to be enough	
}

function showHideTblReal(id, mid){
    tbl = document.getElementById(oid); // note the oid, set in the timeout above
    scrollH = document.getElementById(oid).scrollHeight; // total height of element
    var nId = tbl.id;
    
    if(parseInt(tbl.style.height) <= 110){
        showTbl(nId, scrollH, mid);
        return;
    }
    hideTbl(nId, scrollH, mid);  
}

function cloneObject(what) {
    for (i in what) {
        this[i] = what[i];
    }
}

/// *************************************************///
///            Detail image swap functions  ///
/// *************************************************///
function swap_detail_image(imageToGet, mid, category){
	var hash = new Array('id', mid, 'imageToGet', imageToGet, 'category', category);
	call_ajax(hash, 'detail-large-form-' + mid, 'detail-large-' + mid, 'detail_templates/large_image.php', 'progress_bottom_' + mid, '', '', false);
	
}

/// *************************************************///
///               saved item functions ///
/// *************************************************///

function swap_saved(inID, cat, desc, contact){
	n_count = count; // from ajax call in class

	var ob = window.document.getElementById('saved_' + cat + '_' + inID);
	var si = window.document.getElementById('saved_image_' + inID);
	var hn = window.location.hostname;

	if(ob !== null){ // BUG #156 make sure we can still access that div (lost when we change pages, results etc)
					// canged from a check on si, that's now generic, now we check for ob as that's per cat. 
		if(si.src === "http://sledxchange.com/images_common/saved_items/r_n_saved.gif" || si.src === 'http://www.sledxchange.com/images_common/saved_items/r_n_saved.gif') { 
			//alert('swap: ' + ass);
			if(n_count < 4){ // only swap if less than nessesary number
				ob.innerHTML = "<img src=\"images_common/saved_items/r_saved.gif\" width=\"19\" height=\"79\" border=\"0\" id=\"saved_image_" + inID + "\">";
			}
		} else {
			ob.innerHTML = "<a href=\"javascript:;\" onclick=\"var hash = new Array('id', '" + inID + "', 'Category', '" + cat + "', 'preview_image', 'true', 'description'," + "'" + desc + "', 'contact'," + "'" + contact + "'" + "); call_ajax(hash, 'form_" + inID + "', 'saved-items', 'remote/SavedItems.php', 'progress_search', '', '', false), swap_saved('" + inID + "','"+ cat + "')\"><img src=\"images_common/saved_items/r_n_saved.gif\" width=\"19\" height=\"79\" border=\"0\" id=\"saved_image_" + inID + "\"></a>";
		}
	}
}
p_imageArray = new Object();
p_descriptionArray = new Object();
p_contactArray = new Object();

function add_p_imageArray_item(imgName, src){
	p_imageArray[imgName] = src;
}
function preview(evt, inID, cat){
	if(document.images){
		evt = (evt) ? evt : ((window.event) ? window.event : null);
		if(evt) {
			// use document.documentElement.scrollTop to be DTD compliant, works with IE6+ standards compliant
			if(!window.document.getElementById('popUp')){
				var popUp = document.createElement("DIV");
				//popUp.setAtribute("id", "popUp");
				popUp.id = 'popUp';
				//popUp.style.background = "#FFFAAA";
				//popUp.style.border = "gray solid 1px";
				popUp.style.visibility = "visible";			
				document.body.appendChild(popUp);
			} else {
				var popImage = new Image(100, 73);
				src_a = inID + cat;
				popImage.src = p_imageArray[src_a];
				var popUp = document.getElementById('popUp');
				//popUp.style.width = '246px';
				//popUp.style.height = '161px';
				//popUp.style.backgroundImage = "url(images_saved_items/popup_bg_246_161.gif)";
				popUp.style.lineHeight = "1.5";
				popUp.style.filter = "alpha(opacity=99)";
				popUp.style.MozOpacity = ".99";
				if(popImage.complete){ // make sure image exists before appending to popUp DIV object
					//popUp.appendChild(myImage);
					// BUG #164
					document.getElementById('pi').src = popImage.src;
					//document.getElementById('popPic').appendChild(popImage);
					document.getElementById('popText').innerHTML = decodeBase64(p_descriptionArray[inID + cat]);
					document.getElementById('popContact').innerHTML = decodeBase64(p_contactArray[inID + cat]);
				}
				
				popUp.style.position = 'absolute';
				popUp.style.visibility = 'visible';
				offsetY = document.body.scrollTop;
				offsetX = document.body.scrollLeft;
				if(window.event){ // explorer, safari
					popUp.style.left = (evt.clientX + 5) + document.body.scrollLeft + 'px';
					popUp.style.top = (evt.clientY + 15) + document.documentElement.scrollTop + 'px';
				} else { // ff, moz
					popUp.style.left = (window.scrollX + 5) + evt.clientX + 'px';
					popUp.style.top = (window.scrollY + 15) + evt.clientY + 'px';
				}
			}
		}
	}
}
function hide_preview(){
	if(window.document.getElementById('popUp')){
		var popUp = window.document.getElementById('popUp');
		popUp.style.visibility="hidden";
	}
}

				
function preview_saved_help(evt){
		if(document.images){
		evt = (evt) ? evt : ((window.event) ? window.event : null);
		if(evt) {
			if(!window.document.getElementById('popUp_sh')){ // no loner used as of May 25, v-36
				popUp_sh = document.createElement("div");
				popUp_sh.setAttribute("id", "popUp_sh");
				//popUp_sh.id = 'popUp_sh';
				popUp_sh.style.visibility = "visible";
				
				document.body.appendChild(popUp_sh);
				
				//document.body.appendChild(myImage); // crash safari
				
				var myImage = new Image();
				myImage.src = "../images_common/saved_items/SavedItems_help_popUp.gif";
				
				//alert(myImage.nodeName);
				hj = document.createElement("p");
				hj.innerHTML = 'hixsx';
				//popUp_sh.appendChild(hj);
				
				//document.body.appendChild(myImage);
				document.getElementById("popUp_sh").appendChild(myImage);
				//document.getElementById('popUp_sh').innerHTML = 'hi';
				
			} else {
				
				var popUp_sh = document.getElementById ? document.getElementById('popUp_sh') : document.all ? document.all['popUp_sh'] : document.layers['popUp_sh'];
				popUp_sh.style.position = 'absolute';
				popUp_sh.style.visibility = 'visible';
				popUp_sh.style.zIndex = '99';
				offsetY = document.body.scrollTop;
				offsetX = document.body.scrollLeft;
				if(window.event){ // explorer, safari
					popUp_sh.style.left = (evt.clientX + 5) + document.body.scrollLeft + 'px';
					popUp_sh.style.top = (evt.clientY + 15) + document.documentElement.scrollTop + 'px';
				} else { // ff, moz
					popUp_sh.style.left = (window.scrollX + 5) + evt.clientX + 'px';
					popUp_sh.style.top = (window.scrollY + 15) + evt.clientY + 'px';
				}
			}
		}
	}
}
function hide_preview_saved_help(){
	if(window.document.getElementById('popUp_sh')){
		var popUp_sh = window.document.getElementById('popUp_sh');
		popUp_sh.style.visibility="hidden";
	}
}
/// *************************************************///
///                print functions ///
/// *************************************************///
	var xSize = 700;
	var ySize = 850;
	var toolVal = 0;
	var locVal = 0;
	var statVal = 1;
function open_detail(id){ // called from clicking on images
	imageWindow = window.open("detail_image.php?id=" + id,"ImageView","toolbar=" + toolVal+ ",location=" + locVal + ",status=" + statVal + ",resizable, scrollbars" + ",width=" + xSize + ",height=" + ySize);
}

var printWindow; // name of our window

function printArticle(inID, cat){
	printWindow = window.open("printRecord.php?id=" + inID + "&cat=" + cat, '', 'scrollbars,resizable,width=690px,height=750px');
}

/// *************************************************///
///                contact functions ///
/// *************************************************///
function checkRef(num){ // make sure ref number has been entered correctly. 
	var val = document.getElementById("rx").value;
	//alert(val.value);
	if(val == num){
		//alert('match');
		document.getElementById('rxBut').style.display = 'inline';
	} else {
		//alert('no match');
	}
}

function checkVals(but){
	var trip = false;
	for(var i = 0; i < but.form.elements.length; i++){
		if(but.form.elements[i].value == ''){
			if(but.form.elements[i].className != 'noCheck') {
				but.form.elements[i].style.backgroundColor = 'red';
				trip = true;
			}
		} else {
			but.form.elements[i].style.borderColor = '';
		}
	}
	if(trip){
		document.getElementById('submitHelp').style.display = 'block';
		return false;
	} else {
		return true;
	}
}

var tx = 400;
function update(elm) {
	var counter = document.getElementById('counter');
	var description = elm.value;
	var desc_length = description.length;
	var old = counter.value;
	//alert(description.length);
	counter.value = desc_length;
	if(counter.value > tx && old <= tx) {
 		alert('Too many characters entered!');
 		if(document.styleSheets) {
   			counter.style.fontWeight = 'bold';
   			counter.style.color = '#ff0000'; 
		} 
	} else if(counter.value <= tx && old > tx && document.styleSheets ) {
   		counter.style.fontWeight = 'normal';
   		counter.style.color = '#000000'; 
	} 
}

/// *************************************************///
///                text edit functions ///
/// *************************************************///
function showMCE(id){
    tinyMCE.execCommand('mceAddControl', false, id);	
}

function clearBlogForm(){
	document.getElementById('blog_comment').value = ""; 	
}


/**********************************************************************
TERMS OF USE - EASING EQUATIONS
Open source u?der the BSD License.
Copyright (c) 2001 Robert Penner
JavaScript version copyright (C) 2006 by Philippe Maegerman
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
   * Neither the name of the author nor the names of contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************/
function Delegate() {}
Delegate.create = function (o, f) {
	var a = new Array() ;
	var l = arguments.length ;
	for(var i = 2 ; i < l ; i++) a[i - 2] = arguments[i] ;
	return function() {
		var aP = [].concat(arguments, a) ;
		f.apply(o, aP);
	}
}

Tween = function(obj, prop, func, begin, finish, duration, suffixe){
	this.init(obj, prop, func, begin, finish, duration, suffixe)
}
var t = Tween.prototype;

t.obj = new Object();
t.prop='';
t.func = function (t, b, c, d) { return c*t/d + b; };
t.begin = 0;
t.change = 0;
t.prevTime = 0;
t.prevPos = 0;
t.looping = false;
t._duration = 0;
t._time = 0;
t._pos = 0;
t._position = 0;
t._startTime = 0;
t._finish = 0;
t.name = '';
t.suffixe = '';
t._listeners = new Array();	
t.setTime = function(t){
	this.prevTime = this._time;
	if (t > this.getDuration()) {
		if (this.looping) {
			this.rewind (t - this._duration);
			this.update();
			this.broadcastMessage('onMotionLooped',{target:this,type:'onMotionLooped'});
		} else {
			this._time = this._duration;
			this.update();
			this.stop();
			this.broadcastMessage('onMotionFinished',{target:this,type:'onMotionFinished'});
		}
	} else if (t < 0) {
		this.rewind();
		this.update();
	} else {
		this._time = t;
		this.update();
	}
}
t.getTime = function(){
	return this._time;
}
t.setDuration = function(d){
	this._duration = (d == null || d <= 0) ? 100000 : d;
}
t.getDuration = function(){
	return this._duration;
}
t.setPosition = function(p){
	this.prevPos = this._pos;
	var a = this.suffixe != '' ? this.suffixe : '';
	this.obj[this.prop] = Math.round(p) + a;
	this._pos = p;
	this.broadcastMessage('onMotionChanged',{target:this,type:'onMotionChanged'});
}
t.getPosition = function(t){
	if (t == undefined) t = this._time;
	return this.func(t, this.begin, this.change, this._duration);
};
t.setFinish = function(f){
	this.change = f - this.begin;
};
t.geFinish = function(){
	return this.begin + this.change;
};
t.init = function(obj, prop, func, begin, finish, duration, suffixe){
	if (!arguments.length) return;
	this._listeners = new Array();
	this.addListener(this);
	if(suffixe) this.suffixe = suffixe;
	this.obj = obj;
	this.prop = prop;
	this.begin = begin;
	this._pos = begin;
	this.setDuration(duration);
	if (func!=null && func!='') {
		this.func = func;
	}
	this.setFinish(finish);
}
t.start = function(){
	this.rewind();
	this.startEnterFrame();
	this.broadcastMessage('onMotionStarted',{target:this,type:'onMotionStarted'});
	//alert('in');
}
t.rewind = function(t){
	this.stop();
	this._time = (t == undefined) ? 0 : t;
	this.fixTime();
	this.update();
}
t.fforward = function(){
	this._time = this._duration;
	this.fixTime();
	this.update();
}
t.update = function(){
	this.setPosition(this.getPosition(this._time));
	}
t.startEnterFrame = function(){
	this.stopEnterFrame();
	this.isPlaying = true;
	this.onEnterFrame();
}
t.onEnterFrame = function(){
	if(this.isPlaying) {
		this.nextFrame();
		setTimeout(Delegate.create(this, this.onEnterFrame), 0);
	}
}
t.nextFrame = function(){
	this.setTime((this.getTimer() - this._startTime) / 1000);
	}
t.stop = function(){
	this.stopEnterFrame();
	this.broadcastMessage('onMotionStopped',{target:this,type:'onMotionStopped'});
}
t.stopEnterFrame = function(){
	this.isPlaying = false;
}

t.continueTo = function(finish, duration){
	this.begin = this._pos;
	this.setFinish(finish);
	if (this._duration != undefined)
		this.setDuration(duration);
	this.start();
}
t.resume = function(){
	this.fixTime();
	this.startEnterFrame();
	this.broadcastMessage('onMotionResumed',{target:this,type:'onMotionResumed'});
}
t.yoyo = function (){
	this.continueTo(this.begin,this._time);
}

t.addListener = function(o){
	this.removeListener (o);
	return this._listeners.push(o);
}
t.removeListener = function(o){
	var a = this._listeners;	
	var i = a.length;
	while (i--) {
		if (a[i] == o) {
			a.splice (i, 1);
			return true;
		}
	}
	return false;
}
t.broadcastMessage = function(){
	var arr = new Array();
	for(var i = 0; i < arguments.length; i++){
		arr.push(arguments[i])
	}
	var e = arr.shift();
	var a = this._listeners;
	var l = a.length;
	for (var i=0; i<l; i++){
		if(a[i][e])
		a[i][e].apply(a[i], arr);
	}
}
t.fixTime = function(){
	this._startTime = this.getTimer() - this._time * 1000;
}
t.getTimer = function(){
	return new Date().getTime() - this._time;
}
Tween.backEaseIn = function(t,b,c,d,a,p){
	if (s == undefined) var s = 1.70158;
	return c*(t/=d)*t*((s+1)*t - s) + b;
}
Tween.backEaseOut = function(t,b,c,d,a,p){
	if (s == undefined) var s = 1.70158;
	return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
}
Tween.backEaseInOut = function(t,b,c,d,a,p){
	if (s == undefined) var s = 1.70158; 
	if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
	return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}
Tween.elasticEaseIn = function(t,b,c,d,a,p){
		if (t==0) return b;  
		if ((t/=d)==1) return b+c;  
		if (!p) p=d*.3;
		if (!a || a < Math.abs(c)) {
			a=c; var s=p/4;
		}
		else 
			var s = p/(2*Math.PI) * Math.asin (c/a);
		
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	
}
Tween.elasticEaseOut = function (t,b,c,d,a,p){
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
	}
Tween.elasticEaseInOut = function (t,b,c,d,a,p){
	if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) var p=d*(.3*1.5);
	if (!a || a < Math.abs(c)) {var a=c; var s=p/4; }
	else var s = p/(2*Math.PI) * Math.asin (c/a);
	if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
}

Tween.bounceEaseOut = function(t,b,c,d){
	if ((t/=d) < (1/2.75)) {
		return c*(7.5625*t*t) + b;
	} else if (t < (2/2.75)) {
		return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
	} else if (t < (2.5/2.75)) {
		return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
	} else {
		return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
	}
}
Tween.bounceEaseIn = function(t,b,c,d){
	return c - Tween.bounceEaseOut (d-t, 0, c, d) + b;
	}
Tween.bounceEaseInOut = function(t,b,c,d){
	if (t < d/2) return Tween.bounceEaseIn (t*2, 0, c, d) * .5 + b;
	else return Tween.bounceEaseOut (t*2-d, 0, c, d) * .5 + c*.5 + b;
	}

Tween.strongEaseInOut = function(t,b,c,d){
	return c*(t/=d)*t*t*t*t + b;
	}

Tween.regularEaseIn = function(t,b,c,d){
	return c*(t/=d)*t + b;
	}
Tween.regularEaseOut = function(t,b,c,d){
	return -c *(t/=d)*(t-2) + b;
	}

Tween.regularEaseInOut = function(t,b,c,d){
	if ((t/=d/2) < 1) return c/2*t*t + b;
	return -c/2 * ((--t)*(t-2) - 1) + b;
	}
Tween.strongEaseIn = function(t,b,c,d){
	return c*(t/=d)*t*t*t*t + b;
	}
Tween.strongEaseOut = function(t,b,c,d){
	return c*((t=t/d-1)*t*t*t*t + 1) + b;
	}

Tween.strongEaseInOut = function(t,b,c,d){
	if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
	return c/2*((t-=2)*t*t*t*t + 2) + b;
	}

OpacityTween.prototype = new Tween();
OpacityTween.prototype.constructor = Tween;
OpacityTween.superclass = Tween.prototype;

function OpacityTween(obj,func,fromOpacity,toOpacity,duration){
	this.targetObject = obj;
	this.init(new Object(),'x',func,fromOpacity,toOpacity,duration);
}
var o = OpacityTween.prototype;
o.targetObject = {};
o.onMotionChanged = function(evt){
	var v = evt.target._pos;
	var t = this.targetObject;
	t.style['opacity'] = v / 100;
	t.style['-moz-opacity'] = v / 100;
	if(t.filters) t.filters.alpha['opacity'] = v;
}

/*
License
This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
*/
function urlDecode(str){
    str=str.replace(new RegExp('\\+','g'),' ');
    return unescape(str);
}
function urlEncode(str){
    str=escape(str);
    str=str.replace(new RegExp('\\+','g'),'%2B');
    return str.replace(new RegExp('%20','g'),'+');
}

var END_OF_INPUT = -1;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}
function readBase64(){    
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}
function encodeBase64(str){
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT){
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT){
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT){
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            } else {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76){
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}
function readReverseBase64(){   
    if (!base64Str) return END_OF_INPUT;
    while (true){      
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
    return END_OF_INPUT;
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}

function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}

var digitArray = new Array('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f');
function toHex(n){
    var result = ''
    var start = true;
    for (var i=32; i>0;){
        i-=4;
        var digit = (n>>i) & 0xf;
        if (!start || digit != 0){
            start = false;
            result += digitArray[digit];
        }
    }
    return (result==''?'0':result);
}

function pad(str, len, pad){
    var result = str;
    for (var i=str.length; i<len; i++){
        result = pad + result;
    }
    return result;
}

function encodeHex(str){
    var result = "";
    for (var i=0; i<str.length; i++){
        result += pad(toHex(str.charCodeAt(i)&0xff),2,'0');
    }
    return result;
}

function decodeHex(str){
    str = str.replace(new RegExp("s/[^0-9a-zA-Z]//g"));
    var result = "";
    var nextchar = "";
    for (var i=0; i<str.length; i++){
        nextchar += str.charAt(i);
        if (nextchar.length == 2){
            result += ntos(eval('0x'+nextchar));
            nextchar = "";
        }
    }
    return result;
    
}