var _keepalive = false;
function keepalive()
{
	if (_keepalive==false) 
	{ 
		_keepalive = new Ajax('/keepalive.php', {onComplete:function(m){
				if ($('live_counter')!=undefined) $('live_counter').innerHTML = m;
		}}); 
	}
	else
		_keepalive.request();
	setTimeout('keepalive()',30000);
}

window.addEvent('domready', keepalive);

function _rollover(obj,r) { _assign(obj,obj.src,r); } function _assign(obj,s,r) { obj.onmouseover = function() { obj.src = r; }; obj.onmouseout = function() { obj.src = s; }; obj.border=0; obj.onload=''; }
function togglelogin() {
	if (parseInt($('login').style.marginTop) >= 0)
	{
		new Fx.Style('login', 'margin-top',{duration:100}).start(20, -150);
	}
	else
	{
		new Fx.Style('login', 'margin-top',{duration:100}).start(-150, 20);
	}
}
function _t_sel(obj,ID,platform) {
	// find all li, toggle
	var sstr = '_t_'+ID;
	var i;

	var li = obj.parentNode.parentNode.getElementsByTagName('li');
	for(i=0;i<li.length;i++) li[i].className = '';
	obj.parentNode.className = 'active';
	
	// find all div, toggle
	var div = $(sstr).getElementsByTagName('div');
	for(i=0;i<div.length;i++) 
		if (/^_t_/.test(div[i].id)) div[i].style.display = 'none';
	
	$(sstr+'_'+platform).style.display = '';
	Cookie.set('_t_selected['+ID+']', platform, {path: '/'});
}

function set_currency(c) {
	Cookie.set('webox_currency', c, {path: '/'});
	document.location.reload();
}
function change_boxart(id,platform)
{
	$('pd_ba'+id).src = '/boxart/'+platform+'/'+id+'/sf';
}
var scroll_index = new Array();
var scroll_fx = new Array();
function scroll_slider(div,n,total_n)
{
	var step = 132;
	 
	if (scroll_fx[div]==undefined)
		scroll_fx[div] = new Fx.Style(div, 'margin-left', {duration:500, onStart:function(){this.running=true;}, onComplete:function(){this.running=false;}});

	if (scroll_fx[div].running) { return; }

	if (scroll_index[div]==undefined) scroll_index[div] = 0;
	
	if (scroll_index[div] == 0 && n < 0) 
	{
		// at left most, and click left again
		scroll_index[div] = total_n-4;
	}
	else if (scroll_index[div] == (total_n-4) && n > 0) 
	{
		// at right most, click right again
		scroll_index[div] =0; 	
	}
	else
	{ 
		scroll_index[div] += n;
		if (scroll_index[div]<0) scroll_index[div] = 0;
		if (scroll_index[div]>total_n-4) scroll_index[div] = total_n-4;
	}
	if (scroll_index[div]<0) scroll_index[div] = 0;
	scroll_fx[div].start(-1 * scroll_index[div] * step); 
}


function add_to_cart(platform, id, btn)
{
	notify_addcart('Adding ...');
	btn.disabled = true;
	var myAjax = new Ajax('/cart.php', {method: 'post', data: $('fcart_'+platform+id), update: $('cart_status'), evalScripts: true, onComplete:function(){ btn.disabled = false; cart_qty_status();}}).request();
}
function del_item(id,is_cart)
{
	var str;
	str = 'a=ajax_remove&i='+id;
	var myAjax = new Ajax('/cart.php', {method: 'post', postBody:str, update: $('cart_status'), onComplete:function(){cart_qty_status(is_cart)}}).request();
}
function cart_qty_status(is_cart)
{
	var myAjax = new Ajax('/cart.php', {method: 'post', postBody:'a=ajax_cart_qty_status', update: $('cart_qty_status')}).request();
}

function add_feedback(id)
{
	$('fba'+id).style.display='none';
	var myAjax = new Ajax('/membership.php?a=ajax_add_feedback&order_id='+id, {update: $('fb_'+id), evalScripts: true }).request();

}

function save_feedback(form)
{
	$('fba'+form.order_id.value).style.display='none';
	var myAjax = new Ajax(form.action, {data:form, method:'post', update: $('fb_'+form.order_id.value), evalScripts: true }).request();
}

function add_promo_code(code)
{
	var myAjax = new Ajax('/cart.php?a=ajax_add_promo_code&code='+code.value, { update: $('cart_status'), evalScripts: true}).request();
}

function center_div(div)
{
	var sz = window.getSize();
	var wsz = $(div).getSize();

    $(div).style.top =  ((sz.size.y-wsz.size.y)/2)+'px';
	$(div).style.left = ((sz.size.x-wsz.size.x)/2)+'px';
	
}

var notify_fx = false;
function notify_addcart(msg)
{
	if (!$('notify_addcart'))
	{
		// create it
		var x = document.createElement('div');
		x.id = 'notify_addcart';
		document.body.appendChild(x);
		notify_fx = new Fx.Style('notify_addcart','opacity',{duration:2000, onComplete:function(){$('notify_addcart').style.display='none';}});
	}
	$('notify_addcart').innerHTML = msg;
	$('notify_addcart').style.display = '';
	center_div('notify_addcart');
	notify_fx.stop();
	notify_fx.start(2,0);
}


function check_invite(f)
{
	if (f.name.value == '')
	{
		alert('Please enter your name');
		f.name.focus();
		return false;
	} 
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	if (f.email.value=='' || !filter.test(f.email.value))
	{
		alert('Please enter your email address');
		f.email.select();
		f.email.focus();
		return false;
	}
	return true; 
}

function redeem_item(id,d,p,mp)
{	
	$('fredeem_'+id).submit.disabled = true;
	if (mp == 0) 
	{
		window.location = '/membership.php?a=login&msg=Please Login to redeem.';
		return;
	}
	if ($('fredeem_'+id).q.value <= 0)
	{
		alert('Qty cannot be zero or less than zero');
		return;
	}
	if ((p*parseInt($('fredeem_'+id).q.value)) <= mp)
	{
		if (confirm('Are you sure to redeem '+d+'?\nPoint needed: '+(p*parseInt($('fredeem_'+id).q.value))+'.\nYour current point: '+mp+'.'))
		{
			
			var myAjax = new Ajax(
				'/redemption.php?a=redeem&id='+id, {
					method: 'post',
					update: 'test',
					evalScripts: true,
					data: $('fredeem_'+id), 				
					onComplete: function(m) 
					{
//						alert(m);
//						window.location = m;
					}
				}).request();
		}
		else
		$('fredeem_'+id).submit.disabled = false;
	}
	else
	{
		alert('Insufficient Point.');
	}
}

function check_confirm()
{
	if (confirm('Are you sure to confirm this redemption?'))
	return true;
	else
	return false;
}

/* shipping drag n drop */
var shipping_combine;

var posfix = function(draggable) {
    draggable.setStyles({ left:0+"px", top:0+"px"  });
}
var optDropzone = {
    over: function() {
        this.addClass("dragenter");
    },
    leave: function() {
        this.removeClass("dragenter");
    },
    drop: function(draggable) {
		this.removeClass("dragenter");

		var dragId = draggable.id;
		var droppedIn = draggable.getParent().id;

        //$('log-write').setText('Draggable '+dragId+' dropped in '+this.id);
        
        var drag_date = $(draggable.id).getElement('span').innerHTML;
		if (drag_date > this.id)
		{
		    alert('Cannot ship before item\'s available date.');
		    return;
		}

		shipping_combine[shipping_combine.length] = { from: dragId, to: this.id };
		// confirm move
		var div = this.getElementsByTagName('div');
		draggable.injectBefore(div[div.length-1]);
		posfix(draggable);
		toggle_ship_declar(this);
   }
}
var optDraggable = {
    onStart: function(draggable) {
        draggable.setOpacity(0.5).setStyle("z-index", 1);
    },
    onComplete: function(draggable) {
        draggable.setOpacity(1.0).setStyle("z-index", 0);
        posfix(draggable);
        toggle_ship_declar(this);
    }
}
function init_drags() {
    optDraggable.droppables = $$(".dropzone").addEvents(optDropzone);
    $$(".draggable").makeDraggable(optDraggable);
    $$(".draggable").each(function(elm){ posfix(elm) });
}

function combine_shipping()
{
	var data = '';
    shipping_combine.each(function(c){
        data +=  c.from + '=' + c.to + '&';
	});
	new Ajax('/cart.php?a=shipping_options',{data:data, update:'shipping_options',evalScripts:true}).request();
}

function reset_shipping()
{
	new Ajax('/cart.php?a=shipping_options&reset=1',{update:'shipping_options',evalScripts:true}).request();
}

var r_;
var c_;

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		return false
	 }

	 if (str.indexOf(" ")!=-1){
		return false
	 }

	 return true
}

function calc_shipping()
{
	total_amount = parseFloat(document.rcv.total_amount.value);
	var sm = document.getElementById('sm');
	var input = sm.getElementsByTagName("input");
	var label = sm.getElementsByTagName("label");
	var shipping_cost = 0;

	for(i=0;i<input.length;i++)
	{
	    if(input[i].className=='ship_date') continue;
	    
		if (!/^Standard/i.test(input[i].value) && !/^Free UPS/i.test(input[i].value))
		{
			/*if (document.rcv.buyer_country.value=='Germany')
			{
				input[i].disabled=true;
			}
			else
			{
				input[i].disabled=false;
			}*/

		
//		alert(input[i].name);
			var str = input[i].value.split(',');
			var cost = parseFloat(r_[str[0]][document.rcv.buyer_country.value]);
			if (input[i].checked) shipping_cost = parseFloat(shipping_cost + cost);

			if (r_[str[0]][document.rcv.buyer_country.value]==undefined)
				r_[str[0]][document.rcv.buyer_country.value]=15;

			var t = label[i].getElementsByTagName('span');
			t[0].innerHTML = parseFloat(cost);
			input[i].value = str[0]+','+cost;
		}
		/*else if (/^Standard/i.test(input[i].value) && document.rcv.buyer_country.value=='Germany')
		{
			input[i].checked = true;
		}*/
// 		else if (/^Super Express/i.test(input[i].value) && input[i].checked)
// 		{
// 			shipping_cost = shipping_cost + parseFloat(r_['SUPER EXPRESS'][document.rcv.buyer_country.value]);
// 		}

	}
	document.rcv.total_amt.value = 	parseFloat(total_amount + shipping_cost).toFixed(2);
}

function empty(e, msg)
{
    if (e.value == '')
    {
        alert(msg);
        e.focus();
        return true;
    }

    return false;
}

function submitcheck()
{
	if (empty(document.rcv.buyer_name, 'Please input Your First Name'))
        return false;
    if (empty(document.rcv.buyer_email, 'Please input Your Email'))
        return false;
    if (!echeck(document.rcv.buyer_email.value))
    {
    	alert("Your Email address is invalid");
    	document.rcv.buyer_email.focus();
    	return false;
    }

   	if (empty(document.rcv.buyer_addr1, 'Please input Your Address'))
        return false;
   	if (empty(document.rcv.buyer_postcode, 'Please input Your Post Code'))
        return false;
   	if (empty(document.rcv.buyer_city, 'Please input Your City'))
        return false;


	// if online payment accepted
   	if (document.rcv.payment_method != undefined && empty(document.rcv.payment_method, 'Please select Payment Type'))
    	return false;
	// check term & condition
	if(!$('agreed').checked){
		alert('Please agree with terms & condition before you proceed to payment');
		return false;
	}

	document.rcv.proceed.disabled = 1;
  	document.rcv.proceed.value = 'Submitting...';

  	return true;
}

function toggle_ship_declar(ele){
	try{
        var parent_tr = ele.parentNode.parentNode;
	}catch(ex){
		return;
	}

	var express_input = $(parent_tr).getElement('input.Express');
	var showDeclar = express_input.checked;
	var div_dropzone = $(parent_tr).getElement('div.dropzone');
	var dropzone_items = $(div_dropzone.id).getElements('div.draggable');
	for(var i=0;i<dropzone_items.length;i++){
		//alert(dropzone_items[i].id);
		declar_line_id = 'ship_declar_'+dropzone_items[i].id;
		showDeclarItem(declar_line_id,showDeclar);
	}
}
