function select(el, val) {
	for(var i=0; i<$(el).getElementsByTagName('option').length; i++) {
		if($(el).getElementsByTagName('option')[i].value == val)
			$(el).selectedIndex = i;
	}
}

function loadingStart() {
	var div_content = '<h2 id="loding_text">Loading ...</h2><div id="loading_div" style="height:' + getPageHeight() + 'px;">&nbsp;</div>';
	new Insertion.Before($('wrapper'), div_content);
	$('loding_text').style.top = getCenter('loding_text') + "px";
}

function setSelectOptions(selectObj, allOptions, selectedOption) {
	for(prop in allOptions)
	{
		var text = '';
		var selected = (selectedOption == prop) ? true : false;
		
		text = allOptions[prop]['name'];
		
		if (navigator.appName == "Microsoft Internet Explorer")
			selectObj.add(new Option(text, prop, selected, selected));
		else
			selectObj.add(new Option(text, prop, selected, selected), null);
	}
	
	return;
}

function getPageing(pages, page)
{
	var url = "javascript:search_result('$P');";
	var rage = 4;
	var html = '';
	
	pages = parseInt(pages);
	page = parseInt(page);
	
	if (pages) {
		
		html += '<ul>';
		
		if(page > 1)
			html += '<li><a href="' + url.replace('$P', (page - 1)) + '"><<</a> </li>';
		
		if((page - rage) > 2)
			html += '<li> <a href="' + url.replace('$P', '1') + '">1...</a></li>';
			
		pages_show_start = (page-rage > 0 ? (page - rage) : 1);
		pages_show_end = (page > rage ? (page + rage) : (page + (2 * rage - page + 1)));
		
		for (i=pages_show_start; i<=pages_show_end; i++ ) {
			html += '<li><a href="' + url.replace('$P', i) + '"' + (i == page ? ' class="page_selected"' : '') + '>' + i + '</a> <li>';
			
			if(pages == i) break;
		}
		
		if((page + rage + 4) < pages)
			html += '<li><a href="' + url.replace('$P', pages) + '">...' + pages + '</a></li>';
		
		if(page < pages)
			html += '<li> <a href="' + url.replace('$P', (page + 1)) + '">>></a></li>';
		
		html += '</ul>';
	}
	
	return html;
}

function showSearchForm(result)
{
	hideSearchForm();	
	loadingStop();
	
	// Used to create a search results form. 
	// It adds categories (options) to the select box 'category_id' 
	// Then it gives a list of our search results (div).
	
	if (result.page != '0') {
		
		$('first_step_upload').style.display = 'none';
		$('results').style.display = 'block';
	}
	
	if (navigator.appName == "Microsoft Internet Explorer")
		$('category_id').add(new Option('', 0));
	else
		$('category_id').add(new Option('', 0), null);
	setSelectOptions($('category_id'), result.categories, result.category_id); 

	$('found_results').innerHTML = "Results Found: " + result.found_rows;
	
	$('pagging').innerHTML = getPageing(result.all_pages, result.page);
		
	if (result.page_rows > 0)
	{
		
		var result_div_html = "";
		for (var i=0; i<result.page_rows; i++)
		{
			result_div_html += '<div><img src="'+result.search_results[i].img+'" /><span>'+result.search_results[i].title+'</span>';
			result_div_html += '<button type="button" onClick="video_upload('+result.search_results[i].srid+')">' + result.button_text + '</button></div>';
		}
		new Insertion.Bottom($('resultsdiv'), result_div_html);
		$('no_results').style.display = "none";
	}
	else
	{
		$('no_results').style.display = "block";
	}
	
	$('upload_search').style.display = 'block';
	$('upload_search').style.top = (getScrollTop() + 40) + 'px';
	
	var div_content = '<div id="search_form_wrapper" style="height:' + getPageHeight() + 'px;">&nbsp;</div>';
	new Insertion.Before($('wrapper'), div_content);
}

function hideSearchForm()
{
	if ($('search_form_wrapper')) $('search_form_wrapper').style.display = 'none';
	if ($('upload_search')) $('upload_search').style.display = 'none';
}

function loadingStop() {
	if ($('loding_text')) $('loding_text').remove();
	if ($('loading_div')) $('loading_div').remove();
}

function proccess() {
	loadingStart();
	var scripttag = document.getElementsByTagName('script')[0];
	wwwbase = scripttag.src.match(/(.*)\/js.*/)[1]+'/';
	var url = wwwbase + 'ajax/process_payment/';
	var pars = '';
	new Ajax.Request( url, { method: 'post', parameters: pars, onComplete: AjaxComplete } );
}

function AjaxComplete(respond) {
	eval("var result = "+respond.responseText+";");
	loadingStop();

	if(result.error) {
		if(typeof $('help') == 'undefined')
			new Insertion.Before($('shipping'), '<div id="help" class="warning">'+result.error_message+'</div>');
		else
			$('help').innerHTML = result.error_message;
	}
	else
		window.location = wwwbase+'products/order_finished'
}

function setFilterPrice(min, max, form) {
	document.getElementById('min_amount').value = min;
	document.getElementById('max_amount').value = max;
	document.getElementById('filterForm').submit();
}

function changeState(val, id1, id2) {
	if(val == 'US') {
		document.getElementById(id1).style.display = 'inline';
		document.getElementById(id1).disabled = false;
		document.getElementById(id2).style.display = 'none';
		document.getElementById(id2).disabled = true;
	}
	else {
		document.getElementById(id1).style.display = 'none';
		document.getElementById(id1).disabled = true;
		document.getElementById(id2).style.display = 'inline';
		document.getElementById(id2).disabled = false;
	}
}

function changePayment(type) {
	var elms = new Array(document.getElementById('ptype1'), document.getElementById('ptype2'), document.getElementById('ptype3'));
	for(var i = 0; i<elms.length; i++)
		if(type == i+1)
			elms[i].style.display = 'block';
		else
			elms[i].style.display = 'none';
}

function show_promo(what, header) {
	var elms = document.getElementById('home_right').getElementsByTagName('ul');
	for(var i=0; i<elms.length; i++)
		if(elms[i].id != "")
			elms[i].style.display = elms[i].id != "wp"+what ? "none" : "block";
	document.getElementById('home_right').getElementsByTagName('h3')[1].innerHTML = header;
}

function video_upload(productId)
{
	var url = wwwbase + 'videos/upload/' + productId;
	
	document.location = url;
}

function search_result(page)
{
	// if this is the (n+1)-th time we are recieving results, we should delete the overall div layer
	var url = wwwbase + 'products/search_upload';
	
	var pars = 'page=' + page;	
	if ($('category_id')) {
		pars += '&category_id=' + $('category_id').value;
	}
	if ($('query')) {
		pars += '&query=' + $('query').value;
	}
		
	loadingStart();
	new Ajax.Request( url, { method: 'post', parameters: pars, onComplete: recieveSearchResults } );
}

function getEventKeyCode(event)
{	
	if (navigator.appName == "Microsoft Internet Explorer")
		return event.keyCode;
	else
		return event.which;	
}

function recieveSearchResults (request)
{
	eval("var result = " + request.responseText + ";");

	if ($('category_id'))
	{
		// collect child elements
		new Element.replace('resultsdiv', '<div id="resultsdiv"></div>');
		new Element.replace('category_id', '<select id="category_id" name="category_id"><option value="0"/></select>');
	}
	showSearchForm(result);
}

function onsendData (originalRequest) {
	eval("var result = "+originalRequest.responseText+";");
	loadingStop();

}

function showImage(src) {
	
	var loading_div = document.createElement("div");
	loading_div.setAttribute("id", "loading_div");
	loading_div.setAttribute("style", "height:" + getPageHeight() + "px");
	
	var div = document.createElement("div");
	div.setAttribute("id", "preview_image");
	div.setAttribute("style", "top:" + (getScrollTop() + 40) + "px");
	
	var a = document.createElement("a");
	a.setAttribute("id", "preview_image_a");
	a.setAttribute("href", "javascript: closeImage();");
	a.innerHTML = 'X';
	
	var img = document.createElement("img");
	img.setAttribute("src", src);
	
	if (img.width == 0) {
		img.onload = function() {
			this.width = this.width > 1000 ? 1000 : this.width;
			a.style.left = (parseInt(this.width/2)-5).toString() + "px";
		}
	} else {
		img.width = img.width > 1000 ? 1000 : img.width;
		a.style.left = (parseInt(img.width/2)-5).toString() + "px";
	}
	
	div.appendChild(a);
	div.appendChild(document.createElement("br"));
	div.appendChild(img);
	
	new Insertion.Before($('wrapper'), div);
	new Insertion.Before($('wrapper'), loading_div);
}

function closeImage() {
	$('preview_image').remove();
	$('loading_div').remove();
}

function getScrollTop() {
	if (window.pageYOffset)
		return window.pageYOffset;
	if (document.documentElement)
		return document.documentElement.scrollTop;
	if (document.body)
		return document.body.scrollTop;
}

function getClientHeight() {
	if (window.pageYOffset)
		return window.innerHeight;
	if (document.documentElement)
		return document.documentElement.clientHeight;
	if (document.body)
		return document.body.clientHeight;
}

function getPageHeight() {
	
	if ($('wrapper').offsetHeight < getClientHeight()) {
		height = getClientHeight();
	} else {
		height = $('wrapper').offsetHeight;
	}
	return height;
}

function getCenter(id) {
	
	var scrollTop = getScrollTop();
	var clientHeight = getClientHeight();

	return scrollTop + clientHeight/2 - $(id).clientHeight/2 - 50;
}

function showConfirm(msg, url, yesMsg, noMsg) {
	
	closeConfirm();
	
	var div_content = '<div id="confirm_alert" class="alert">';
	div_content += '<div class="msg">';
	div_content += msg;
	div_content += '<br /><br /><a href="' + url + '">' + yesMsg + '</a>';
	div_content += '<a href="javascript: closeConfirm();">' + noMsg + '</a>';
	div_content += '</div>';
	div_content += '</div>';
	div_content += '<div id="loading_div" style="height:' + getPageHeight() + 'px;">&nbsp;</div>';
	new Insertion.Before($('wrapper'), div_content);
	
	$('confirm_alert').style.top = getCenter('confirm_alert') + 'px';
}

function closeConfirm() {
	if ($('confirm_alert')) $('confirm_alert').remove();
	if ($('loading_div')) $('loading_div').remove();
}

function showAlert(msg, okMsg) {
	
	closeAlert();
	
	var div_content = '<div id="alert" class="alert">';
	div_content += '<div class="msg">';
	div_content += msg;
	div_content += '<br /><br /><a href="javascript: closeAlert();">' + okMsg + '</a>';
	div_content += '</div>';
	div_content += '</div>';
	div_content += '<div id="loading_div" style="height:' + getPageHeight() + 'px;">&nbsp;</div>';
	new Insertion.Before($('wrapper'), div_content);
	
	$('alert').style.top = getCenter('alert') + 'px';
}

function closeAlert() {
	if ($('alert')) $('alert').remove();
	if ($('loading_div')) $('loading_div').remove();
}

function submitSearchForm(inputId, msg, okMsg) {
	var value = $(inputId).value;
	if(value == '' || value.length < 3)
	{
		showAlert(msg, okMsg);
	} else {
		search_result('1');
	}
}
	
function changeVerificationImage(link)
{
	link.childNodes[0].src = link.childNodes[0].src + '/+';
}

function ExpandCollapse(to_hide, this_object)
{
	if (document.getElementById(to_hide).style.display == 'none')
	{
		var str = this_object.src;
		str = str.replace(str.substr(str.lastIndexOf('/')+1, str.length), 'section_arrow_up.png');
		this_object.src = str;
		this_object.alt = 'Collapse';
		this_object.title = 'Collapse';
		document.getElementById(to_hide).style.display = 'block';
	}
	else
	{
		var str = this_object.src;
		str = str.replace(str.substr(str.lastIndexOf('/')+1, str.length), 'section_arrow.png');
		this_object.src = str;
		this_object.alt = 'Expand';
		this_object.title = 'Expand';
		document.getElementById(to_hide).style.display = 'none';
	}
}

var DRG = {

	obj : null,
	
	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= DRG.start;

		o.hmode = bSwapHorzRef? false : true;
		o.vmode = bSwapVertRef? false : true;

		o.root = oRoot && oRoot != null? oRoot : o;

		if (o.hmode && isNaN(parseInt(o.root.style.left  ))) o.root.style.left = 0;
		if (o.vmode && isNaN(parseInt(o.root.style.top   ))) o.root.style.top = 0;
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right = 0;
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = 0;

		o.minX	= typeof minX != 'undefined'? minX : null;
		o.minY	= typeof minY != 'undefined'? minY : null;
		o.maxX	= typeof maxX != 'undefined'? maxX : null;
		o.maxY	= typeof maxY != 'undefined'? maxY : null;

		o.xMapper = fXMapper? fXMapper : null;
		o.yMapper = fYMapper? fYMapper : null;

		o.root.onDragStart = new Function;
		o.root.onDragEnd = new Function;
		o.root.onDrag = new Function;
	},

	start : function(e)
	{
		var o = DRG.obj = this;
		e = DRG.fixE(e);
		var y = parseInt(o.vmode? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode? o.root.style.left : o.root.style.right );
		
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= DRG.drag;
		document.onmouseup		= DRG.end;

		return false;
	},

	drag : function(e)
	{
		e = DRG.fixE(e);
		var o = DRG.obj;

		var ey = e.clientY;
		var ex = e.clientX;
		var y = parseInt(o.vmode? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode? 1 : -1));

		if (o.xMapper)	nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		DRG.obj.root.style[o.hmode? "left" : "right"] = nx + "px";
		DRG.obj.root.style[o.vmode? "top" : "bottom"] = ny + "px";
		DRG.obj.lastMouseX	= ex;
		DRG.obj.lastMouseY	= ey;
		
		/* this writes togeter with drag action */
		DRG.obj.root.onDrag(nx, ny);
		
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		
		/* this writes end result of the drag action */
		DRG.obj.root.onDragEnd(parseInt(DRG.obj.root.style[DRG.obj.hmode? "left" : "right"]), 
		 parseInt(DRG.obj.root.style[DRG.obj.vmode ? "top" : "bottom"]));
		
		DRG.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};


var SCR = {

	tid : null, 
	
	step : 20, 
	
	obj : null, 
	
	slidBarH : null, 
	
	slider : null, 
	
	arrUp : null, 
	
	arrDown : null, 
	
	k : 1,
	
	moveScroll : function (Y)
	{
	  SCR.obj.scrollTop = Y * SCR.k;
	},
	
	moveSlider : function ()
	{
  	SCR.slider.style.top = SCR.obj.scrollTop/SCR.k + 'px';
	},
	
	scrollIt : function (action)
	{
		if(action != null)
			SCR.tid = setTimeout(function ()
				{
					SCR.obj.scrollTop += SCR.step * action;
					SCR.moveSlider();
					SCR.scrollIt(action);
				}
				, 100);
		else
			clearTimeout(SCR.tid);
	},
	
	arrEvInit : function ()
	{
	  SCR.arrUp.onmouseover = new Function('SCR.scrollIt(-1)');
	  SCR.arrDown.onmouseover = new Function('SCR.scrollIt(1)');
	  SCR.arrUp.onmouseout = SCR.arrDown.onmouseout = new Function('SCR.scrollIt()');
	},
	
	arrStopInit : function ()
	{
	  SCR.arrDown.onmouseover = SCR.arrUp.onmouseover = function (e){ DRG.fixE(e).cancelBubble = true; }
	},
	
	/* mouse wheel */
	
	myScroll : function (onwheel)
	{
		if(onwheel){
			if (window.addEventListener)
				/** DOMMouseScroll is for mozilla. */
				window.addEventListener('DOMMouseScroll', SCR.wheel, false);
			/** IE/Opera. */
			window.onmousewheel = document.onmousewheel = SCR.wheel;
		}
		else
		{
			if (window.removeEventListener)
				/** DOMMouseScroll is for mozilla. */
				window.removeEventListener('DOMMouseScroll', SCR.wheel, false);
			window.onmousewheel = document.onmousewheel = null;
		}
	},
	
	handle : function (delta) 
	{
		if (delta < 0)
			SCR.obj.scrollTop += SCR.myScroll? SCR.step : 0;
		else
			SCR.obj.scrollTop -= SCR.myScroll? SCR.step : 0;
			
		SCR.moveSlider();
	},
	
	wheel : function (event)
	{
	    var delta = 0;
	    if (!event) /* For IE. */
	            event = window.event;
	    if (event.wheelDelta) { /* IE/Opera. */
	            delta = event.wheelDelta/120;
	            /** In Opera 9, delta differs in sign as compared to IE. */
	            if (window.opera)
	                    delta = delta;
	    } else if (event.detail) { /** Mozilla case. */
	            delta = -event.detail/3;
	    }
	    if (delta)
	            SCR.handle(delta);
	    if (event.preventDefault)
	            event.preventDefault();
	            
			event.returnValue = false;
	},
	
	/* mouse wheel end */
	
	init : function (id, slBg, slBut, slUp, slDown, slPos)
	{ 
		SCR.obj = $(id);
		SCR.slidBarH = $(slBg).offsetHeight;
		SCR.slider = $(slBut);
		
		SCR.k = (SCR.obj.scrollHeight - SCR.obj.offsetHeight)/(SCR.slidBarH - SCR.slider.offsetHeight);
		
		SCR.arrUp = $(slUp);
		SCR.arrDown = $(slDown);
		
		SCR.arrEvInit();
		
		$(slBg, 1).visibility = $(slUp, 1).visibility = $(slDown, 1).visibility = SCR.obj.scrollHeight > 
		SCR.obj.offsetHeight? "visible" : "hidden";
		SCR.obj.scrollTop = slPos? slPos : 0;
		SCR.slider.style.top = SCR.obj.scrollTop + 'px';
		
		DRG.init(SCR.slider, SCR.slider, 0, 0, 0, SCR.slidBarH - SCR.slider.offsetHeight);
		
		SCR.obj.onmouseover = function (){ SCR.myScroll(1); } 
		SCR.obj.onmouseout = function (){ SCR.myScroll(); }
		
		SCR.slider.onDragStart = function (x, y){ SCR.arrStopInit(); };
		SCR.slider.onDrag = function (x, y){ SCR.moveScroll(y); };
		SCR.slider.onDragEnd = function (x, y){ SCR.arrEvInit(); };
	}
};

/* DOM functions */

function $(id, f){
	return eval('document.getElementById(id)' + (f? '.style' : ''));
}

function _(o, _e, id, f){
	return eval('o.getElementsByTagName(_e)[' + (id? id : 0) + ']' + (f? '.style' : ''));
}


function change_paytype(pay_type, div_name1, div_name2)
{
	switch (pay_type)
	{
		default:
		case 0:
			$(div_name1).style.display = 'none';
			$(div_name2).style.display = 'none';
			break;
		case 1:
			$(div_name1).style.display = 'block';
			$(div_name2).style.display = 'none';
			break;
		case 2:
			$(div_name1).style.display = 'none';
			$(div_name2).style.display = 'block';
			break;
	}
}

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 '';
}

function showLoginForm(javascriptExecute)
{	
	hideLoginForm();
	
	$('register_popup').style.display = 'block';
	$('register_popup').style.top = (getScrollTop() + 40) + 'px';
	
	var div_content = '<div id="register_popup_wrapper" style="height:' + getPageHeight() + 'px;">&nbsp;</div>';
	new Insertion.Before($('wrapper'), div_content);
	
	setCookie('jscript', javascriptExecute, 1);
}

function hideLoginForm()
{
	if ($('register_popup_wrapper')) $('register_popup_wrapper').style.display = 'none';
	if ($('register_popup')) $('register_popup').style.display = 'none';
}

function showVideoFeedbackForm(javascriptExecute)
{	
	hideLoginForm();
	
	$('video_feedback').style.display = 'block';
	$('video_feedback').style.top = (getScrollTop() + 40) + 'px';
	
	var div_content = '<div id="video_feedback_wrapper" style="height:' + getPageHeight() + 'px;">&nbsp;</div>';
	new Insertion.Before($('wrapper'), div_content);
	
	setCookie('jscript', javascriptExecute, 1);
}

function hideVideoFeedback()
{
	if ($('video_feedback_wrapper')) $('video_feedback_wrapper').style.display = 'none';
	if ($('video_feedback')) $('video_feedback').style.display = 'none';
}

window.onload = function() {
	var scripttag = document.getElementsByTagName('script')[0];
	wwwbase = scripttag.src.match(/(.*)\/js.*/)[1]+'/';
	
	if(document.getElementById('uploadFormId') != null && document.getElementById('uploadFormId') != "undefined") {
		new FileUploader('uploadFormId', 'uprocess');
	}
	
	var script = getCookie('jscript');
	if (script != '') {
		eval(script);
		setCookie('jscript', '', -1);
	}
}

function expandText(textID)
{
	$(textID).innerHTML = $('fullText').value;
	$('seeMore').setStyle({visibility: 'hidden'});
	$('seeLess').setStyle({visibility: 'visible'});
}

function collapseText(textID)
{
	var pos = 0;
	for (var c=200; c>0; c--)
	{
		if ($(textID).innerHTML[c] == ' ')
		{
			pos = c;
			break;
		}
	}
	
	$(textID).innerHTML = $(textID).innerHTML.substring(0,200-(200-pos))+'...';
	$('seeLess').setStyle({visibility: 'hidden'});
	$('seeMore').setStyle({visibility: 'visible'});
}