/**
* Return the Y page's position
*/
function getY(){
	var posY = 0;
	// With Mozilla
	if (window.innerHeight){
		posY = window.pageYOffset;
	// With Internet Explorer (if there is 'DOCTYPE' header)
	}else if (document.documentElement.scrollTop){
		posY = document.documentElement.scrollTop;
	// With Internet Explorer (without 'DOCTYPE' header)
	}else if (document.body){
		posY = document.body.scrollTop;
	}
	return posY;
}

function getX(){
	var posX = 0;
	posX = ($(document).width())/2-(parseInt($('#noticeArea').width())/2);

	return posX;
}
function Agent() { }

Agent.prototype._getValue = function(elementId) {
	try{
		return $('#'+elementId).val();
	}catch(e){
		alert(elementId+' is not valid!');
	}
}

Agent.prototype.chooseLocation = function(location){
	$.ajax({
		data:{
			action: "chooseLocation",
			country_code : location
		}
	});
	agent.load(' ',1);
	return true;
}

Agent.prototype.getClientHeight = function(){
	var winH = 0;
	if (navigator.appName.indexOf("Microsoft")!=-1)
		winH = document.body.offsetHeight;
	else
		winH = window.innerHeight;
	return winH;
}

Agent.prototype.getClientWidth = function(){
	var winW=0;
	if (navigator.appName.indexOf("Microsoft")!=-1)
		winW = document.body.offsetWidth;
	else
		winW = window.innerWidth;

	return winW;
}

Agent.prototype._stickOnTop = function(elementId){
	var clientHeight = this.getClientHeight();

	if (window.innerHeight)
		pos = window.pageYOffset;
	else if (document.documentElement && document.documentElement.scrollTop)
		pos = document.documentElement.scrollTop;
	else if (document.body)
		pos = document.body.scrollTop

	if (pos < this._stickOnTop_theTop)
		pos = this._stickOnTop_theTop;
	else
		pos += this._stickOnTop_theTop;

	$(elementId).style.top = pos+'px';
	//temp = setTimeout('agent._stickOnTop("'+elementId+'")',100);
}


Agent.prototype.shopAddShoppingCartItem = function(productTypeTitle,productId,price,productBundleId){
	if(!productBundleId) productBundleId = 0;
	$.ajax({
		data:{
			action:'shopAddShoppingCartItem',
			productTypeTitle:productTypeTitle,
			productId:productId,
			price:price,
			productBundleId:productBundleId
		}
	});
}


Agent.prototype.shopProcessShoppingCartPayment = function(shipAddressId,billAddressId){
	$.ajax({
		data: {
			action : "shopProcessShoppingCartPayment",
			shipAddressId : shipAddressId,
			billAddressId : billAddressId
		}
	});
}

Agent.prototype.userLogin = function(){
	$.ajax({
		data:{
			action:'userLogin',
			username: this._getValue("userLoginUsername") ,
			password: this._getValue("userLoginPassword") ,
			remember: ($("#userLoginRemember").attr("checked") ? 1 : 0)  ,
			return_action: this._getValue("userLoginReturnAction")
		}
	});
}

Agent.prototype.userLogout = function(){
	$.ajax({
		data:{
			action:'userLogout'
			}
	});
}

Agent.prototype.userSendLogin = function(){
	$.ajax({
		data : {
			action : "userSendLogin",
			username : this._getValue("userLoginAssistantUserName"),
			email : this._getValue("userLoginAssistantEmail")
		}
	});
}

Agent.prototype.userUpdatePassword = function(){
	$.ajax({
		data : {
			action : "userUpdatePassword",
			existing_password : this._getValue("userExistingPassword"),
			password : this._getValue("userPassword"),
			retype_password : this._getValue("userRetypePassword"),
			id : this._getValue("userId")
		}
	});
}


Agent.prototype.miscProductGlscKoscCalculateRate = function(){
	$.ajax({
		data : {
			action : 'miscProductGlscKoscCalculateRate',
			from_product_kos_county_id : this._getValue("fromProductKosCountyId"),
			product_kos_country_rate_id : this._getValue("productKosCountryRateId")
		}
	});
}

Agent.prototype.miscProductGlscKoscRefreshDestinationCallTypes = function(){
	$.ajax({
		data : {
			action : "miscProductGlscKoscRefreshDestinationCallTypes",
			product_kos_country_id : $("#toProductKosCountyId").val()
		}
	});
}

Agent.prototype.userCheckLogin = function(redirectToUrl){
	$.ajax({
			data:{
				action:'userCheckLogin',
				redirectToUrl:redirectToUrl
			}
		});
}

Agent.prototype.CancelTransaction = function(id){
if(!confirm('Are you sure you\'ve confirmed this order?'))return false;
	$.ajax({
		data:{
		action:'transactionCancel',
		id:id
		}
	});
}


Agent.prototype.userTransactionItemRefund = function() {
	transactionItemIds = new Array();
	$('input[@name=transactionItemIds][checked]').each(function(i){
			transactionItemIds[i] = $(this).val();
	});

	if (!transactionItemIds)return false;
	if (confirm('You are making a new refund transaction. Are you sure you want to do this?')) {
		$.ajax({
			data: {
				action: 'userTransactionItemRefund',
				'transactionItemIds[]': transactionItemIds,
				transactionId: $('input[@name=transactionId]').val()
			}
		});
	}
}

Agent.prototype.userTransactionItemItemCheck= function(checkbox, transactionItemId){
	if($(checkbox).attr("checked")){
		$.ajax({
			data: {
				action: 'userTransactionItemSelect',
				'transactionItemIds[]': transactionItemId
			}
		});

	}else{
		$.ajax({
			data: {
				action: 'userTransactionItemDeSelect',
				'transactionItemIds[]': transactionItemId
			}
		});

	}
}

Agent.prototype.userTransactionItemItemSelectAll = function(){
	transactionItemIds = new Array();
	$("input[@name='transactionItemIds']").each(function(i) {
		$(this).attr("checked", true);
		transactionItemIds[i] = $(this).val();
	});
	$.ajax({
		data: {
			action: 'userTransactionItemSelect',
			'transactionItemIds[]': transactionItemIds
		}
	});
}
Agent.prototype.userTransactionItemItemDeSelectAll = function(){
	transactionItemIds = new Array();
	$("input[@name='transactionItemIds'][checked]").each(function(i) {
		$(this).attr("checked", false);
		transactionItemIds[i] = $(this).val();
	});
	$.ajax({
		data: {
			action: 'userTransactionItemDeSelect',
			'transactionItemIds[]': transactionItemIds
		}
	});
	//agent.load(' ',1);
}
Agent.prototype.userTransactionItemItemInverseSelected = function(){
	selectedTransactionItemIds = new Array();
	unSelectedTransactionItemIds = new Array();
	$("input[@name='transactionItemIds']").each(function() {
		if($(this).attr("checked"))
		{
			$(this).attr("checked", false);
			unSelectedTransactionItemIds.push($(this).val());
		}
		else
		{
			$(this).attr("checked", true);
			selectedTransactionItemIds.push($(this).val());
		}
	});

	$.ajax({
		data: {
			action: 'userTransactionItemDeSelect',
			'transactionItemIds[]': unSelectedTransactionItemIds
		}
	});

	$.ajax({
		data: {
			action: 'userTransactionItemSelect',
			'transactionItemIds[]': selectedTransactionItemIds
		}
	});
}
/**
Agent.prototype.transactionProductRefund = function(){
	var productIdStr = '';
	$('input[@name=prdoctIds]').each(function(){
		if($(this).attr('checked'))
			productIdStr += $(this).val() + ',';
	});

	if (productIdStr == '')
		return false;
	$.ajax({
		data:{
			action: "transactionRefund",
			productIdStr: productIdStr,
			productquantity: $('productquantity').val(),
			transactionId: $('input[@name=transactionId]').val()
		}
	});
	return true;
}
**/
var ajaxError = function(XMLHttpRequest, textStatus, errorThrown){
	alert(
		'Error occurred during interaction with the server, please report to the system administrator!\n'
		+XMLHttpRequest.responseText
	);
	return false;
};

var ajaxSuccess = function(xml){
	$(xml).find('ajax-response').children().each(function(){
		switch($(this).attr('type')){
			case 'element':
				$('#'+$(this).attr('id')).html($(this).text());
			break;
			case 'refresh':
				location.reload(true);
			break;
			case 'redirect':
				document.location =$(this).attr('value');
			break;
			case 'notice':
				$('#noticeArea').html($(this).attr('value'))
					.css({position:"absolute",top:String(getY()+10)+"px",left:String(getX())+"px",display:"block"})
					.animate({opacity: 1.0}, 3000)
					.fadeOut('slow',function(){
						$(this).hide();
					});
			break;
			case 'newWindow':
				self.window.open($(this).attr('value'));
			break;
			case 'back':
				self.window.history.go(-1);
			break;
			default:
				alert('No sepcial action assigned for callback, pelase check!');
			break;
		}
	})
};

$(function(){
	DEBUG = false;
	$.ajaxSetup({
		url:"/core/service.php?brand_name=agent",
		type:"POST",
		dataType:"xml",
		global:true,
		error:ajaxError,
		success:ajaxSuccess
		});
	agent = new Agent();
	textareas = new Array();	//For tinyMCE
});
