// Header javascript Functions

var cTarget;
var cTargetLink;
var cTargetTglActive;
function checkCloseElement(e){
	var target = (e && e.target) || (event && event.srcElement);
	var obj = cTarget;
	var obj2 = cTargetLink;
	if (checkParent(target, obj, obj2)) {
		obj.style.display='none';

		$('mt_iframe').style.display = $('advanced_search').style.display;
		if (cTargetTglActive) cTargetLink.toggleClassName('active');

		document.onclick=null;
	}
}

function checkParent(t, obj, obj2){
	while(t.parentNode){
		if(t==obj || t==obj2){
			return false
		}
		t=t.parentNode
	}
	return true
}


function clearInitValue()
{
	if (document.forms[0].search.value == 'Start your search here') {
		document.forms[0].search.value = '';
	}
}

function toggleCatHover()
{
	toggleSelectBoxes($('cat_hover'));

	//hideAdvancedSearch();

	$('cat_hover').toggle();
    
	$('cat_hover_link').toggleClassName('active');

	cTarget = $('cat_hover');
	cTargetLink = $('cat_hover_link');
	cTargetTglActive = 1;
	document.onclick=checkCloseElement;
}

function toggleAdvancedSearch()
{
	//hideCatHover();
	$('advanced_search').toggle();
	$('mt_iframe').style.display = $('advanced_search').style.display;
	$('advanced_search_link').toggleClassName('active');
	cTarget = $('advanced_search');
	cTargetLink = $('advanced_search_link');
	cTargetTglActive = 1;
	document.onclick=checkCloseElement;
}

function hideAdvancedSearch()
{
	$('advanced_search').hide()
	$('mt_iframe').style.display = $('advanced_search').style.display;
	$('advanced_search_link').removeClassName('active');
}

function hideCatHover()
{
    if($('cat_hover'))
    {
        $('cat_hover').hide();
    }
	if($('cat_hover_link'))
    {
        $('cat_hover_link').removeClassName('active');
    }
}

function toggleSelectBoxes(e)
{
	if(document.all){

	}
}




function getCities(selectObj)
{
	ajaxresp = new Ajax.Request('ajax/getCities.php', {
		method: 'get',
		onSuccess: function(resp) {
			respXML = resp.responseXML;

			//respXML.getElementsByTagName("status")[0].childNodes[0].nodeValue;
			var option =  Element.create('option');
			option
			selectObj.appendChild()
		}
	});
}

function advSearchKeyCatSelect(catId, form, root)
{   
	if (form.search.value && form.search.value != 'Start your search here') {
		form.category.value = catId;
		form.submit();
	}
	else {
        jumpCategory(root,catId);
	}

}
function advSearchKeyCatSelectAll(form)
{
	$('cat_hvr_a').innerHTML = 'Select Category';
	form.category.value = 0;
	toggleCatHover();
}

// ----------------------------

function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1;
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    }
  }
return "";
}

/**
 * used in input forms where the submit button is an a link
 */
function onClickSubmit(e, form) {
	var keynum;

	if(window.event) { // IE
  		keynum = e.keyCode;
  	} else if(e.which) { // Netscape/Firefox/Opera
  		keynum = e.which;
  	}

  	if (keynum == 13) form.submit();
}

function gotoUrl(loc) {
	window.location = loc;
}

function setClass(e, s) {
	e.setAttribute('class', s);
	e.setAttribute('className', s);
}

function remove(s) {
	s.parentNode.removeChild(s);
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');

		ele.className=ele.className.replace(reg,' ');
	}
}

function hasClass(ele,cls) {
	if (ele && cls) {
		return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
	}
}

function initFormErrorHandler() {
	$$('input.field_error').each(function(s) { removeClass(s, 'field_error') });
	$$('select.field_error').each(function(s) { removeClass(s, 'field_error') });

	$$('div.field_error_msg').each(function(s) { remove(s) });
}

function raiseFormError(formElement, errorMsg) {
	addClass(formElement,"field_error");

	var error_div = document.createElement('DIV');
	addClass(error_div, 'field_error_msg');
	error_div.innerHTML = errorMsg;

	formElement.parentNode.appendChild(error_div);

	return 1; // used to make error checking more compact
}


function showFormErrorsMsg(element, usermsg) {
	if ($('form-error-message')) {
		return 0; // the error message already exists, no need to do anything else
	}


	var dl = document.createElement('DL');
	var dt = document.createElement('DT'); // dl -> dt
	var dd;
	var ul = document.createElement('UL'); // dl -> dd -> ul
	var li = document.createElement('LI'); // dl -> dd -> ul -> li

	var msg;


	dl.setAttribute('id', 'system-message');

	setClass(dt, 'message');


	dt.setAttribute('id', 'form-error-message');

	//if (isIE) {
	//	dd = document.createElement('DD class="error message fade"');  // dl -> dd
	//}
	//else {
		dd = document.createElement('DD');  // dl -> dd

		setClass(dd, 'error message fade')

	//}

	dl.appendChild(dt);
	dl.appendChild(dd);

	dd.appendChild(ul);
	ul.appendChild(li);

	if (usermsg.Length > 0) {
		msg = usermsg;
	}
	else {
		msg = 'You need to fix the errors in the form below';
	}
	li.innerHTML = msg;


	element.appendChild(dl);
}

function charCount(obj, num){
	var objCount;
	for(var i = obj; i != null; i=i.parentNode){
		if(i.tagName && i.tagName.toLowerCase() == 'tr'){
			objCount = i.getElementsByTagName('strong')[0];
			break;
		}
	}
	if (objCount != null){
		objCount.innerHTML = num - obj.value.length;
	}
}


function fnRemoveElementsFromNode(obj, subTagName){
	var optEls = obj.getElementsByTagName(subTagName);
	var i = 0;
	while (optEls[i]){
		optEls[i].parentNode.removeChild(optEls[i]);
	}
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            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 +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._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);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	var fakefield = document.createElement('input');
	fakeFileUpload.className = 'fakefile';
	fakefield.className = 'fakefield';
	fakeFileUpload.appendChild(fakefield);
	var image = document.createElement('img');
	image.src='../uploaded_files/document_uploads/blank.gif';
	image.className = 'fakebutton';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		var filed = x[i].parentNode;
		x[i].className = 'file';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
			this.parentNode.getElementsByTagName('img')[0].style.backgroundPosition = '0 0';
		}
		x[i].onmouseover = function () {
			this.parentNode.getElementsByTagName('img')[0].style.backgroundPosition = '0 -18px';
		}
	}
}

function getPhotoForSample(spl_Name, tag_id, intWidth, intHeight, num){
	spl_Name = spl_Name.replace(' ', '%20');
	spl_Name = spl_Name.replace('/thumb_', '/');
	document.getElementById('Org_' + tag_id).width = intWidth;
	document.getElementById('Org_' + tag_id).height = intHeight;
	document.getElementById('Org_' + tag_id).style.backgroundImage = 'url(' + spl_Name + ')';
	document.getElementById('num_' + tag_id).innerHTML = num;
}

function getPhotoSlide(tag_id, mode){
	var aryRow = document.getElementById('inf_' + tag_id).innerHTML.split(';')
	var num = parseInt(document.getElementById('num_' + tag_id).innerHTML);
	aryRow.pop();
	switch (mode){
		case 'prev':
			num = ((num-1) < 0)?(aryRow.length-1):(num-1);
		break;
		case 'next':
			num = ((num+1) >= aryRow.length)?0:(num+1);
		break;
		default:
		break;
	}
	var aryDetail = aryRow[num].split(',');
	var bgImg = document.getElementById('thumbImg_'+num).style.backgroundImage;
	bgImg = bgImg.replace(' ', '%20');
	bgImg = bgImg.replace('/thumb_', '/');
	document.getElementById('Org_' + tag_id).width = aryDetail[0];
	document.getElementById('Org_' + tag_id).height = aryDetail[1];
	document.getElementById('Org_' + tag_id).style.backgroundImage = bgImg;
	document.getElementById('num_' + tag_id).innerHTML = num;
}

//
// Payment option selection
//
function showPaypalMethod() {
	hideAllMethods();

	$('paypal').show();
}

function showCreditCardMethod() {
	hideAllMethods();

	$('credit_card').show();
}

function showCouponMethod() {
	hideAllMethods();

	$('coupon').show();
}

function hideAllMethods() {
	$('credit_card').hide();
	$('coupon').hide();
	$('paypal').hide();
}

function jumpCategory(_webroot, _cat)
{
    document.location = _webroot+'public_panel/cat_home.php?pgs=0&scy=2&smd=1&mode=a&r=3&q=0&lc=0&ls=0&la=1&rc=0&sortCategory=1&sortMode=1&sortCategory=2&sortMode=1&ctg='+_cat;
}

function WBM_doNothing()
{
    return;
}
