function AjaxServer()
{
	this.data = "";
	this.animate = false;
	this.animateType = "showHide";
	this.targetDivId = "";
	this.action = "";
	this.activate = function()
	{
		if(this.animate == true && $("#"+this.targetDivId).css('display') != 'none')
		{
			switch(this.animateType)
			{
			case "showHide":
			  $("#"+this.targetDivId).hide('fast');
			  break;    
			case "fadeInOut":
			  $("#"+this.targetDivId).fadeOut('slow');
			  break;
			default:
			  $("#"+this.targetDivId).hide('fast');
			}
		}
		$("#"+this.targetDivId).load(baseurl+"ajax_server.php", { 'action': this.action} );
		if(this.animate == true)
		{
			switch(this.animateType)
			{
			case "showHide":
			  $("#"+this.targetDivId).show('fast');
			  break;    
			case "fadeInOut":
			  $("#"+this.targetDivId).fadeIn(2000);
			  break;
			default:
			  $("#"+this.targetDivId).show('fast');
			}
			
		}
	};
}



//extends array class to detect a value
Array.prototype.detect = function(itemToDetect)
{
	var j = 0;
    while (j < this.length) 
    {
	    if (this[j] == itemToDetect) 
	    {
	    	return true;
	    } 
	    else { j++; }
    }
    return false;
};

//extends array class to remove a value
Array.prototype.remove = function(itemToRemove)
{
	var j = 0;
    while (j < this.length) 
    {
	    if (this[j] == itemToRemove) 
	    {
	      this.splice(j, 1);
	    } 
	    else { j++; }
    }
    return this;
};

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}


function StringControl()
{
	this.checkMail = function(mail)
	{
		var x = mail;
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		if (filter.test(x)) return 'true';
		else return 'false';
	};
	
	this.urlEncode = function (str) 
	{
		str = escape(str);
		return str.replace(/[*+\/@]|%20/g,
		function (s) 
		{
			switch (s) 
			{
			case "*": s = "%2A"; break;
			case "+": s = "%2B"; break;
			case "/": s = "%2F"; break;
			case "@": s = "%40"; break;
			case "%20": s = "+"; break;
			}
		return s;
		}
		);
	};
	
	this.urlDecode = function(piece)
	{
		return decodeURIComponent(piece);
	};
}


function TimeControl()
{
	this.getDateTime = function()
	{
		thisDate = new Date();
		var month = thisDate.getMonth() + 1;
		if (month < 10){
			month = "0" + month;
			}
		var day = thisDate.getDate();
		if (day < 10){
			day = "0" + day;
			}
		var year = thisDate.getFullYear();
		var hours = thisDate.getHours();
		if (hours < 10){
			hours = "0" + hours;
			}
		var minutes = thisDate.getMinutes();
		if (minutes < 10){
			minutes = "0" + minutes;
			}

		var seconds = thisDate.getSeconds();
		if (seconds < 10){
			seconds = "0" + seconds;
			}

		return year+'-'+month+'-'+day+' '+hours+':'+minutes+':'+seconds;

	};
}
function SiteSearch()
{
	this.page = 1;
	this.find = "shirt";
	this.colors = new Array();
	this.pricerange = "all";
	this.sexes = new Array();
	this.paymethods = new Array();
	this.shops = new Array();
	
	this.doSearch = function()
	{
		// getting serialized strings
		colorstring = this.getSerialized(this.colors);
		paymethodstring = this.getSerialized(this.paymethods);
		shopstring = this.getSerialized(this.shops);
		sexstring = this.getSerialized(this.sexes);
		//query string
		this.find = $("#searchQuery").val();
		//sending page
		extraSend = "";
		if(this.find != "all" && this.find != "" && this.find != site_default_query) { extraSend += "find/"+stringControl.urlEncode(this.find)+"/"; }
		if(colorstring != "all") { extraSend += "colors/"+stringControl.urlEncode(colorstring)+"/"; }
		if(this.pricerange != "all") { extraSend += "prices/"+this.pricerange+"/"; }
		if(sexstring != "all") { extraSend += "sexes/"+sexstring+"/"; }
		if(paymethodstring != "all") { extraSend += "paymethods/"+paymethodstring+"/"; }
		if(shopstring != "all") { extraSend += "shops/"+shopstring+"/"; }
		window.location = baseurl+"search/"+extraSend;
	};
	
	this.clearFilters = function()
	{
		this.sexes = new Array();
		this.paymethods = new Array();
		this.colors = new Array();
		this.shops = new Array();
		this.pricerange = "all";
	};
	
	this.getSerialized = function(anarray)
	{
		thisstring = new String();
		var j = 0;
		while (j < anarray.length) 
	    {
			thisstring += anarray[j];
			if(j < ((anarray.length) - 1)) { thisstring += "_"; }
		    j++;
	    }
		if(thisstring == '') { thisstring = "all"; }
		return thisstring;
	};
	
	this.toggleColor = function(color)
	{
		if(this.colors.detect(color))
		{
			this.colors = this.colors.remove(color);
			$('#img_color_'+color).attr('src', baseurl+'images/filters/filter-color-'+color+'.png');
		}
		else
		{
			this.colors.push(color);
			$('#img_color_'+color).attr('src', baseurl+'images/filters/filter-color-'+color+'-checked.png');
		}
	};
	
	this.setPrice = function(price)
	{
		this.pricerange = price;
	};
	
	this.toggleSexes = function(sex)
	{
		if(this.sexes.detect(sex))
		{
			this.sexes = this.sexes.remove(sex);
			$('#img_sex_'+sex).attr('src', baseurl+'images/filters/filter-'+sex+'.png');
		}
		else
		{
			this.sexes.push(sex);
			$('#img_sex_'+sex).attr('src', baseurl+'images/filters/filter-'+sex+'-checked.png');
		}
	};
	
	this.togglePaymethod = function(paymethod)
	{
		if(this.paymethods.detect(paymethod))
		{
			this.paymethods = this.paymethods.remove(paymethod);
			$('#img_paymethod_'+paymethod).attr('src', baseurl+'images/filters/filter-'+paymethod+'.png');
		}
		else
		{
			this.paymethods.push(paymethod);
			$('#img_paymethod_'+paymethod).attr('src', baseurl+'images/filters/filter-'+paymethod+'-checked.png');
		}
		return true;
	};
	
	this.toggleShop = function(shopid)
	{
		if(this.shops.detect(shopid))
		{
			this.shops = this.shops.remove(shopid);
		}
		else
		{
			this.shops.push(shopid);
		}
	};
}

function showCap(shirtid, random)
{
	if(shirtid == false)
	{
		return false;
	}
	shirtCapLoaded = true;
	if(thisIsInternetExplorer)
	{
		$('#overlay_' + shirtid + '_' + random).show(0, 
				function(e)
				{
					shirtCapLoaded = true;
				}
			);
	}
	else
	{
		$('#overlay_' + shirtid + '_' + random).fadeIn(200, 
			function(e)
			{
				shirtCapLoaded = true;
			}
		);
	}
	
};

function hideAllCaps()
{
	$(".shirtResultMap").each(
			function ()
			  {
				splitted = $(this).attr('id').split('_');
				hideCap(splitted[1], splitted[2]);
			  }
	);
}

function checkHideIt()
{
	if(stillhovering == false)
	{
		hideAllCaps();
		$("#shirtPreview").fadeOut("fast");
		shirtInspectIdLoaded = "";
	}
}

function hideCap(shirtid, random)
{
	if(shirtid == false)
	{
		return false;
	}
	if(thisIsInternetExplorer)
	{
		$('#overlay_' + shirtid + '_' + random).hide(0, 
				function(e)
				{
					shirtCapLoaded = false;
				}
			);
	}
	else
	{
		$('#overlay_' + shirtid + '_' + random).fadeOut(150, 
			function(e)
			{
				shirtCapLoaded = false;
			}
		);
	}
	
	
};
$(document).ready(function() 
{
	$(".shirtLoveAction").click(
			function(e)
			{
				selector = this;
				arr_id = this.id.split("_");
				$.post(baseurl+"ajax_server.php", 
						{ 'shirt_id': arr_id[1], 'action': 'toggleFavoriteShirt' }, function(data){
							if(data == "added")
							{
								if( $(selector).hasClass('shirtDetailAction') )
								{
									$(selector).removeClass('loveAction');
									$(selector).addClass('loveActionMinus');
								}
								else
								{
									$('#bg_show_'+arr_id[1]+'_'+arr_id[2]).css('background-position', 'center -28px');
								}
								$(selector).effect('transfer',{ to: $("#wishlist"), className: 'borderedDarker' },500);
								return false;

							}
							else if(data == "removed")
							{
								if( $(selector).hasClass('deleteWhenFavoriteRemoved') )
								{
									$('#shirtResult_'+arr_id[1]).hide('fast');
								}
								else if( $(selector).hasClass('shirtDetailAction') )
								{
									$(selector).removeClass('loveActionMinus');
									$(selector).addClass('loveAction');
								}
								else
								{
									$('#bg_show_'+arr_id[1]+'_'+arr_id[2]).css('background-position', 'center 0');
								}
								if(! $(selector).hasClass('deleteWhenFavoriteRemoved') )
								{
									siteMessage.showMessage("This shirt was removed from your wishlist", "confirm");
								}
								return false;
								
							}
							else
							{
								siteMessage.showMessage('You have to login to add shirts to your wishlist', "error");
								return false;
							}
						});
				return false;
			}
	);
	
	$("div.shopLoveAction").click(
			function(e)
			{
				selector = this;
				arr_id = this.id.split("_");
				$.post(baseurl+"ajax_server.php", 
						{ 'shop_id': arr_id[1], 'action': 'toggleFavoriteShop' }, function(data){
							if(data == "added")
							{
								$(selector).removeClass('loveAction');
								$(selector).addClass('loveActionMinus');
								siteMessage.showMessage("This shop was added to your favorites", "confirm");
							}
							else if(data == "removed")
							{
								$(selector).removeClass('loveActionMinus');
								$(selector).addClass('loveAction');
								siteMessage.showMessage("This shop was removed from your favorites", "confirm");
							}
							else
							{
								siteMessage.showMessage('You have to login to add shops to your favorites', "error");
							}
						});
			}
	);
});
function SiteMessage()
{
	this.messagetext = "Something went wrong";
	this.type = "normal";
	this.hideTimeout = 4500;
	
	this.showMessage = function(messagetext, type)
	{
		$("#siteMessageText").html(messagetext);
		this.setClass(type);
		//right positioning
		$("#siteMessageContainer").css("position","absolute");
		$(window).resize(this.info_position);
	    $(window).scroll(this.info_position);
	    this.info_position();
	    //show it
		$("#siteMessageContainer").fadeIn(500);
		//hide it after timeout
		setTimeout (function()
				{
					$("#siteMessageContainer").fadeOut('slow');
				}, this.hideTimeout);
	};
	
	this.show = function(messagetext, type)
	{
		this.showMessage(messagetext, type);
	};
	
	this.info_position = function () { 
		var scrollPosition = $(window).scrollTop();
		$("#siteMessageContainer").css("top",scrollPosition +"px");
		$("#siteMessage").css("height","45px");
		//$("#siteMessageContainer").css("width",$(window).width());
	};
	
	this.setClass = function(type)
	{
		$("#siteMessageBox").removeClass();
		$("#siteMessageTop").removeClass();
		switch(type)
		{
			case 'error':
				$("#siteMessageBox").addClass('siteMessageError');			
				$("#siteMessageTop").addClass('siteMessageErrorTop');			
			break;
			case 'confirm':
				$("#siteMessageBox").addClass('siteMessageConfirm');			
				$("#siteMessageTop").addClass('siteMessageConfirmTop');
			break;
			default:
				$("#siteMessageBox").addClass('siteMessageNormal');			
				$("#siteMessageTop").addClass('siteMessageNormalTop');
		}
	};
};
Config = function() {
	this.validColors = new Array();
	this.validColors[0] = 'black';
	this.validColors[1] = 'white';
	this.validColors[2] = 'grey';
	this.validColors[3] = 'orange';
	this.validColors[4] = 'red';
	this.validColors[5] = 'blue';
	this.validColors[6] = 'yellow';
	this.validColors[7] = 'green';
	this.validColors[8] = 'pink';
	this.validColors[9] = 'brown';
};
var baseurl = "http://www.shirtfix.com/";
var site_default_query = "enter search...";
$(document).ready(function() 
{
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ //test for MSIE x.x;
		 thisIsInternetExplorer = true;
		}
	else
	{
		thisIsInternetExplorer = false;
	}
	
	//inits the objects to be used
	stringControl = new StringControl();
	timeControl = new TimeControl();
	siteMessage = new SiteMessage();
	siteSearch = new SiteSearch();
	config = new Config();
	shirtInspectFlag = true;
	shirtInspectBusy = false;
	shirtInspectDisplayed = false;
	shirtInspectHoveringShirt = false;
	shirtInspectIdLoaded = "";
	shirtInspectIdAjax = "";
	shirtCapLoaded = false;

	userHeaderLoaded = false;
	userHeaderBusy = false;
	
	$(document).mousemove(
			function ()
			  {
				if(!userHeaderLoaded && !userHeaderBusy)
				{
					userHeaderBusy = true;
					// HEADER MENU
					$.post(baseurl+"includes/layout/ajax/headermenu/show_user_options_ajax.php", 
					{  }, 
					function(data)
					{
						if(data != "false")
						{
							$("#headerMenuList").append(data);
							$(".ajaxHeaderItem").fadeIn('slow');
						}
						userHeaderLoaded = true;
					});
				}
			  }
	);
	
	
	//overlay
	$(".shirtResultMap *, .shirtResultMap").mouseover(
			function(e)
			{
				stillhovering = true;
				splitted = $(this).attr('id').split('_');
				if(splitted[1]+'_'+splitted[2] != shirtInspectIdLoaded || $('overlay_'+splitted[1]+'_'+splitted[2]).css('display') == 'none')
				{
					splittedPrev = shirtInspectIdLoaded.split('_');
					hideCap(splittedPrev[0], splittedPrev[1]);
					shirtInspectIdLoaded = splitted[1]+'_'+splitted[2];
					shirtInspectHoveringShirt = true;
					//getShirtInspect(splitted[1], splitted[2], true);
					showCap(splitted[1], splitted[2]);
				}
			}
	);
	
	//shirt inspect
	$(".shirtEnlarge").mouseover(
			function(e)
			{
				splitted = $(this).attr('id').split('_');
				
			}
	);
	
	
	/* CONFIG */
		
		xOffset = 100;
		yOffset = 30;
		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$(".shirtEnlarge").hover(function(e){
		splitEnlarge = $(this).attr('id').split('_');
		
		if(shirtInspectIdAjax != splitEnlarge[1])
		{
			$("#shirtPreview").html('loading..');
			$("#shirtPreview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
			//when ID hasn't been loaded yet, get it with ajax
			$.post(baseurl+"includes/layout/ajax/getshirtinspect.php", 
			{ 'id': splitEnlarge[1] }, 
			function(data)
			{
				if(data != "false")
				{
					shirtInspectIdAjax = splitEnlarge[1];
					$("#shirtPreview").html(data);
		  			
				}
				else
				{
					//siteMessage.show("Could not load shirt detail", 'error');
				}
			});
		}
		else
		{
			//when it was loaded, just show it
			$("#shirtPreview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
		}
								
    },
	function(){
		$("#shirtPreview").fadeOut("fast");
    });	
	
	$(".shirtEnlarge").mousemove(function(e){
		$("#shirtPreview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});	
	
	
	
	$("*:not(.shirtResultMap *, .shirtResultMap)").mouseenter(
			function ()
			  {
					stillhovering = false;
					setTimeout('checkHideIt();', 400); 
			  }
	);
	
});
function findValue(li) {
	if( li == null ) return false;

	// if coming from an AJAX call, let's use the CityId as the value
	if( !!li.extra ) var sValue = li.extra[0];

	// otherwise, let's just display the value in the text box
	else var sValue = li.selectValue;

	return sValue;
}

function selectItem(li) {
	var foundId = findValue(li);
	if(foundId)
	{
		$('#shirt_shopid_hidden').val(foundId);
	}
}

function formatItem(row) {
	return row[0];
}

function lookupAjax(){
	var oSuggest = $("#shirt_shopname")[0].autocompleter;

	oSuggest.findValue();

	return false;
}

function validateAddShirtForm()
{
	submit = 1;
	if(document.getElementById('shirt_image_hidden').value == "")
	{ error = 'You have to provide a valid image for this shirt'; submit = 0; }
	if(document.getElementById('shirt_link').value == "" || document.getElementById('shirt_link').value == "http://")
	{ error = 'Please fill in the full link to the website where this product can be bought'; submit = 0; }
	if(document.getElementById('shirt_shopid_hidden').value == "")
	{ error = "Please pick the shop from the list that appears after you start typing the shop's name"; submit = 0; }
	if(document.getElementById('shirt_name').value == "")
	{ error = "Please provide a name for this shirt"; submit = 0; }	
	if(submit == 1)
	{
		checkShirtExists( $('#shirt_name').val(), $('#shirt_shopid_hidden').val(), $('#shirt_link').val());	
	}
	else{
		siteMessage.showMessage(error, 'error');
	}
	return false;
}

//checkers
function checkShirtExists(shirtname, shopid, shirtlink)
{
	$.post(baseurl+"includes/script/ajax/checkers/check_shirt_exists_ajax.php", 
	{ 'shirtname': shirtname, 'shopid' : shopid , 'shirtlink' : shirtlink}, function(data){
  	if(data == "true")
		{
  			siteMessage.showMessage("This shirt is already in our database, please check again", "error");
		}
		else
		{
			checkAddShirtGotcha($('#gotcha_id').val() , $('#gotcha_check').val());
		}
	});
}

function checkAddShirtGotcha(id, answer)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_gotcha_ajax.php", 
	{ 'id': id, 'answer' : answer }, function(data){
	if(data == "true")
	{
		$('#addshirt_form').submit();
	}
	else
	{
		siteMessage.showMessage("The answer to the question was wrong, please think again :)", "error");	
	}
	});
}
function validateAddShopForm()
{
	submit = 1;
	
	if(document.getElementById('shop_website').value == "")
	{ error = "Please provide your shop's website"; submit = 0; }
	if(document.regshop_form.shirt_f.value == false && 
	document.regshop_form.shirt_m.value == false && 
	document.regshop_form.shirt_u.value == false &&
	document.regshop_form.shirt_k.value == false)
	{
		error = 'You do sell at least one type of shirt, right?'; submit = 0;
	}
	if(stringControl.checkMail(document.getElementById('shop_email').value) == "false" && document.getElementById('shop_email').value != "website")
	{
		{ error = 'Not a valid email address, sorry'; submit = 0; }
	}
	
	if(document.getElementById('shop_email').value == "")
	{ error = 'Please enter the email adress of your shop'; submit = 0; }
	if(document.getElementById('shop_name').value == "")
	{ error = 'Please enter the name of your shop'; submit = 0; }
	shopname = document.getElementById('shop_name').value.toString();
	shopnamematch = shopname.match('&')
	if(shopnamematch != null)
	{ error = 'You can not have the character "&" in the shop name'; submit = 0; }
	if(submit == 1)
	{
		checkShopNameExists(document.getElementById('shop_name').value);	
	}
	else{
		siteMessage.showMessage(error, 'error');
	}
}

//checkers
function checkShopNameExists(shopname)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_shop_name_exists_ajax.php", 
	{ 'name': shopname }, function(data){
  	if(data == "true")
		{
  			siteMessage.showMessage("Your shop is already registered!", "error");
		}
		else
		{
			checkShopRegisterGotcha($('#gotcha_id').val() , $('#gotcha_check').val() );
		}
	});
}

function checkShopRegisterGotcha(id, answer)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_gotcha_ajax.php", 
	{ 'id': id, 'answer' : answer }, function(data){
	if(data == "true")
	{
		registershopajax(document.regshop_form.shop_name.value , document.regshop_form.shop_email.value,
				document.regshop_form.shop_website.value , document.regshop_form.shop_phone.value ,
				document.regshop_form.shirt_f.checked, document.regshop_form.shirt_m.checked,
				document.regshop_form.shirt_u.checked, document.regshop_form.shirt_k.checked,
				document.regshop_form.hoodies.checked, document.regshop_form.undies.checked,
				document.regshop_form.bags.checked, document.regshop_form.shoes.checked,
				document.regshop_form.hats.checked, document.regshop_form.accecoires.checked, 			
				getCheckedValue(document.regshop_form.location),
				document.regshop_form.visa.checked, document.regshop_form.mastercard.checked, document.regshop_form.otherccard.checked,
				document.regshop_form.paypal.checked, document.regshop_form.intbanktrans.checked,
				document.regshop_form.cash.checked, document.regshop_form.cheque.checked);
	}
	else
	{
		siteMessage.showMessage("The answer to the question was wrong, please think again :)", "error");		
	}
	});
}

function registershopajax(username, email, website, phone, s_f, s_m, s_u, s_k, hoodies, undies, bags, shoes, hats, acc, location, visa, mastercard, otherccard, paypal, intbanktrans, cash, cheque)
{
	$.get(baseurl+"includes/script/ajax/registershop_ajax.php", 
			{ 
		'shopname': username, 
		'email' : email ,
		'website' : website ,
		'phone' : phone ,
		'shirt_f' : s_f ,
		'shirt_m' : s_m ,
		'shirt_u' : s_u ,
		'shirt_k' : s_k ,
		'hoodies' : hoodies ,
		'undies' : undies ,
		'bags' : bags ,
		'shoes' : shoes ,
		'hats' : hats ,
		'accecoires' : acc ,
		'location' : location ,
		'visa' : visa ,
		'otherccard' : otherccard ,
		'paypal' : paypal ,
		'mastercard' : mastercard ,
		'intbanktrans' : intbanktrans ,
		'cash' : cash ,
		'cheque' : cheque ,
		'sid' : Math.random()
		}
	, function(data){
			if(data == "register_shop_ok")
			{
				window.location = baseurl+"shoptips/";
			}
			else
			{
				siteMessage.showMessage(data, "error");		
			}
			});	
}
//cropper

function updateCoords(c)
{
	$('#x').val(c.x);
	$('#y').val(c.y);
	$('#w').val(c.w);
	$('#h').val(c.h);
};


function checkCoords()
{
	if (parseInt($('#w').val())) return true;
	alert('Please select a crop region then press submit.');
	return false;
};

//saving and updating functions
admin_addshirttosite = function(shirtid)
{
	$.ajax({
		type:'POST', 
		async: false, 
		data: ( { 'value': '1', 'id' : "shirt__"+shirtid+"__shirt_active"  } ),
		url:baseurl+"save/"
	});
	
	$.ajax({
		type:'POST', 
		async: false, 
		data: ( { 'value': 'NOW()', 'id' : "shirt__"+shirtid+"__shirt_insertdate"  } ),
		url:baseurl+"save/"
	});
			
	$('#shirtResult_'+shirtid).hide('slow');
};

admin_addshoptosite = function(shopid)
{
	$.post(baseurl+"save/", 
			{ 'value': '1', 'id' : "shop__"+shopid+"__shop_active"  });
	$('#shopResult_'+shopid).hide('slow');
};

admin_deleteshirt = function(shirtid)
{
	$.post(baseurl+"delete/", 
			{ 'id' : shirtid, 'type' : 'shirt'  }, function(data){
		if(data == "success")
		{
	  		$('#shirtResult_'+shirtid).hide('slow');
		}
		else
		{
			alert(data);
			siteMessage.showMessage("Something went wrong while deleting this shirt", "error");
		}
	});
	
};

admin_toggleColor = function(color, shirtid)
{
	if(config.validColors.detect(color))
	{
		//send request to backend
		$.post(baseurl+"ajax_server.php", 
				{ 'shirt_id' : shirtid, 'color' : color, 'action' : 'toggleAdminColor'  }, function(data){
					if(data != "success")
			{
				siteMessage.show("Something went wrong while changing colors", "error");
				return false;
			}
		});
		
		//change actual color on page
		for(var i=0; i<config.validColors.length; i++) {
			var value = config.validColors[i];
			$('#'+shirtid+'_img_color_'+value).attr('src', baseurl+'images/filters/filter-color-'+value+'.png');
		}
		$('#'+shirtid+'_img_color_'+color).attr('src', baseurl+'images/filters/filter-color-'+color+'-checked.png');
	}
	return true;
};

admin_deleteshop = function(shopid)
{
	$.post(baseurl+"delete/", 
			{ 'id' : shopid, 'type' : 'shop'  }, function(data){
		if(data == "success")
		{
	  		$('#shopResult_'+shopid).hide('slow');
		}
		else
		{
			siteMessage.showMessage("Something went wrong while deleting this shop", "error");
		}
	});
	
};

admin_flagasok = function(shirtid)
{
	$.post(baseurl+"save/", 
			{ 'value': '1', 'id' : "shirt__"+shirtid+"__shirt_active"  });
	$('#shirtResult_'+shirtid).hide('slow');
};

admin_flagShopasok = function(shopid)
{
	$.post(baseurl+"save/", 
			{ 'value': '1', 'id' : "shop__"+shopid+"__active"  });
	$('#shopResult_'+shopid).hide('slow');
};
function validateContactForm()
{
	submit = 1;
	if($('#contact_message').val() == "")
	{ 
		error = 'Please type your message and hit submit'; submit = 0; 
	}
	if(stringControl.checkMail($('#email').val()) == "false")
	{
		{ error = 'Not a valid email address, sorry'; submit = 0; }
	}
	if(submit == 1)
	{
		checkContactGotcha($('#gotcha_id').val(), $('#gotcha_check').val());	
	}
	else
	{
		siteMessage.showMessage(error, "error");
	}
}

function checkContactGotcha(id, answer)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_gotcha_ajax.php", 
	{ 'id': id, 'answer' : answer }, function(data){
	if(data == "true")
	{
		$('#contact_form').submit();
	}
	else
	{
		siteMessage.showMessage("The answer to the question was wrong, please think again :)", "error");		
	}
	});
}
function validateLoginForm()
{
	submit = 1;	
	if(document.getElementById('login_pass').value == "")
	{ error = 'Please gimme a password'; submit = 0; }	
	if(document.getElementById('login_pass').value.length < 5)
	{ error = 'Your password is at least 5 characters long. Trust me. I know.'; submit = 0; }
	if(document.getElementById('login_name').value == "")
	{ error = 'Might I dare ask you to provide a display name?'; submit = 0; }	
	if(submit == 1)
	{
		checkLoginDisplayNameExists(document.getElementById('login_name').value);	
	}
	else{
		siteMessage.showMessage(error, "error");
	}
}

function checkLoginDisplayNameExists(username)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_display_name_exists_ajax.php", 
	{ 'name': username }, function(data){
  	if(data == "true")
		{
  			document.login_form.submit();
		}
		else
		{
			siteMessage.showMessage("This displayname doesn't exist. If you forgot it... well too bad", "error");
		}
	});
}

function loginKeyCheck(e)
{
	   if(document.getElementById('login_name').focused == true || document.getElementById('login_pass').focused == true)
	   {
		   if (window.event) {e=event;} //IE
		   var KeyID = e.keyCode;
		   
		   switch(KeyID)
		   {
		   	  case 13:
		   		validateLoginForm();
		      break;
		   }
	   }
}
function validateSettingsForm()
{
	submit = 1;
	if(document.getElementById('pass1').value != "" || document.getElementById('pass2').value != "")
	{ 
		if(document.getElementById('pass1').value.length < 5 || document.getElementById('pass2').value.length < 5)
		{ error = 'Your password has to be at least 5 characters long'; submit = 0; }
		if(document.getElementById('pass1').value != document.getElementById('pass2').value)
		{ error = "Your two passwords don't match"; submit = 0; }
	}	
	if(document.getElementById('name').value == "")
	{ error = 'No display name?'; submit = 0; }

	if(submit == 1)
	{
		$('#settings_form').submit();
	}
	else{
		siteMessage.showMessage("Error while change settings", error);
	}
}
function validateRecoverinfoForm()
{
	submit = 1;	
	if(document.getElementById('recover_email').value == "")
	{ error = 'Please enter your e-mail address'; submit = 0; }	
	if(submit == 1)
	{
		document.recoverinfo_form.submit();
	}
	else{
		siteMessage.showMessage(error, "error");
	}
}

function recoverKeyCheck(e)
{
	   if(document.getElementById('login_name').focused == true || document.getElementById('login_pass').focused == true)
	   {
		   if (window.event) {e=event;} //IE
		   var KeyID = e.keyCode;
		   
		   switch(KeyID)
		   {
		   	  case 13:
		   		validateRecoverinfoForm();
		      break;
		   }
	   }
}
function validateRegisterForm()
{
	submit = 1;
	if(document.getElementById('pass1').value == "")
	{ error = 'Please choose a password'; submit = 0; }	
	if(document.getElementById('pass1').value.length < 5)
	{ error = 'Your password has to be at least 5 characters long'; submit = 0; }	
	if(document.getElementById('pass1').value != document.getElementById('pass2').value)
	{ error = "Your two passwords don't match"; submit = 0; }	
	if(stringControl.checkMail(document.getElementById('email').value) == "false")
	{
		{ error = 'Not a valid email address, sorry'; submit = 0; }
	}	
	if(document.getElementById('name').value == "")
	{ error = 'No display name?'; submit = 0; }

	if(submit == 1)
	{
		checkRegisterDisplayNameExists(document.getElementById('name').value);	
	}
	else{
		siteMessage.showMessage(error, "error");
	}
}

function checkRegisterDisplayNameExists(username)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_display_name_exists_ajax.php", 
	{ 'name': username }, function(data){
  	if(data == "true")
		{
  			siteMessage.showMessage("This display name is already taken. Please pick another.", "error");
		}
		else
		{
			checkUserEmailExists(document.reg_form.email.value);
		}
	});
}

function checkUserEmailExists(email)
{
	var thisreturn = false;
	$.get(baseurl+"includes/script/ajax/checkers/check_user_email_exists_ajax.php", 
	{ 'email': email }, function(data){
	if(data == "true")
	{
		siteMessage.showMessage("The e-mail adress you provided is already in use.", "error");
	}
	else
	{
		checkGotcha(document.getElementById('gotcha_id').value, document.getElementById('gotcha_check').value);		
	}
	});
}

function checkGotcha(id, answer)
{
	$.get(baseurl+"includes/script/ajax/checkers/check_gotcha_ajax.php", 
	{ 'id': id, 'answer' : answer }, function(data){
	if(data == "true")
	{
		registerajax(
				document.reg_form.name.value , 
				document.reg_form.email.value ,
				document.reg_form.pass1.value ,
				document.reg_form.website.value , 
				getCheckedValue(document.reg_form.location)	
				);
	}
	else
	{
		siteMessage.showMessage("The answer to the question was wrong, please think again :)", "error");		
	}
	});
}

function registerajax(username, email, password, website, location)
{
	$.get(baseurl+"includes/script/ajax/register_ajax.php", 
	{ 'name': username, 'website' : website,  'password' : password, 'email' : email, 'location' : location}, function(data){
		if(data == "registered_user_ok")
		{
			window.location = baseurl+"register/confirm/";
		}
		else
		{
			siteMessage.showMessage(data, "error");		
		}
	});
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

