// Password checking: 2 password fields mut be equal, min 6 chars length
function passIsEqual( pass1ID, pass2ID ) {
	var pass1 =  document.getElementById( pass1ID );
	var pass2 =  document.getElementById( pass2ID );
	if( pass1.value == pass2.value ) {
		return true;
	}
	return false;
}

// Input is not empty
function isNotEmptyField( idElem ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).value != "" && document.getElementById( idElem ).value != "0" ) {
			return true;
		}
		//document.getElementById( idElem ).focus();
	}
	return false;
}

// Value is higher than (integer)
function higherThan( idElem, indexInt ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).value.length > indexInt ) {
			return true;
		}
		//document.getElementById( idElem ).focus();
	}
	return false;
}

// Value is equal (integer)
function equalAs( idElem, indexInt ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).value.length == indexInt ) {
			return true;
		}
		//document.getElementById( idElem ).focus();
	}
	return false;
}

// Radio or checkbox is selected
function isChecked( idElem ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).checked ) {
			return true;
		}
	}
	return false;
}

// Radio or checkbox is selected
function isCheckedMarketing( idElem ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).checked ) {
			return true;
		}
	}
	alert('You can only enter the competition if you agree with the competition terms. Please tick the checkbox underneath the form and try again.');
	return false;
}


// Valid e-mail
function isValidEmail( elem ) {
	str = document.getElementById(elem).value;
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

// Set focus on input
function setFocus( idElem ) {
	document.getElementById( idElem ).focus();
}

// Clear inputvalue
function clearValue( idElem ) {
	document.getElementById( idElem ).value = '';;
}


function setCSSChange( idElem, colorChange ) {
	//document.getElementById( idElem ).style.border = '1px solid #CC0000';;
	document.getElementById( 'l_'+idElem ).style.color = colorChange;;
}

function smartRedirect( url ) {
	if( url != "" ) {
		setTimeout( "document.location.href='"+url+"';", 2000 );
	}
}

function aHref(url) {
	document.location.href = url;
}


function getObj(name){
	if (document.getElementById) {
		this.obj = document.getElementById(name);
		this.style = document.getElementById(name).style;
	} else if (document.all) {
		this.obj = document.all[name];
		this.style = document.all[name].style;
	} else if (document.layers) {
		this.obj = document.layers[name];
		this.style = document.layers[name];
	}
}


var elementList = new Array();
var nameList 	= new Array();

function addElementToListEmpty( element, ename ) {
	elementList[elementList.length] = element;
	nameList[nameList.length] 	= ename;
}

var varErrorString = '';

function validateForm() {
	varErrorString = "";
	var myErrorArray = new Array();
	var myErrorArrayPointer = 0;
	for(var i=0;i<elementList.length;i++) {
		setCSSChange( elementList[i], "#000" );
		if( !isNotEmptyField( elementList[i] ) ) {
			varErrorString = varErrorString + 'Field "' +nameList[i]+ ' is required!\n';
			// dodaj error do listy
			myErrorArray[myErrorArrayPointer] = elementList[i];
			myErrorArrayPointer++;
		}
	}
	if( varErrorString =='' ) {
		return true;
	}
	for(var i=0;i<myErrorArrayPointer;i++) {
		setCSSChange( myErrorArray[i], "#CC0000" );
	}
	setFocus( myErrorArray[0] );
	alert("Please fill in all fileds listed below:\n"+varErrorString);
	return false;
}


var zmienionoUprawnienia = false;

function uprawnieniaZmieniono() {
	if( !zmienionoUprawnienia ) {
		pokazButtony();
	}
	zmienionoUprawnienia = true;
}

function wylaczPrzekierowanie() {
	zmienionoUprawnienia = false;
}


function pokazButtony() {
	document.getElementById('btns-1').style.display='block';
	document.getElementById('btns-2').style.display='block';
}


function sprawdzZmianyUprawnien() {
	if( zmienionoUprawnienia ) {
		//if( confirm( "Czy zapisac zmiany?" ) ) {
			//document.forms[0].submit();
			//self.location.reload();
		//}
	}
}

function isNumeric(expression) {
	var nums = "0123456789";
	if (expression.length==0)
		return false;
	for (var n=0; n < expression.length; n++)
	{
		if(nums.indexOf(expression.charAt(n))==-1)
			return false;
	}
	return true;
}


function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
var letter = email.charAt(i).toLowerCase();
if (validchars.indexOf(letter) != -1)
  continue;
parsed = false;
break;
  }
  return parsed;
}

function isValidEmail(email, required) {
if (required==undefined) {   // if not specified, assume it's required
required=true;
}
if (email==null) {
if (required) {
return false;
}
return true;
}
if (email.length==0) {  
if (required) {
return false;
}
return true;
}
if (! allValidChars(email)) {  // check to make sure all characters are valid
return false;
}
if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
return false;
} else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
return false;
} else if (email.indexOf("@") == email.length) {  // @ must not be the last character
return false;
} else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
} else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
}
return true;
}

function scrollAnswer( answerID ) {
document.getElementById('answer_'+answerID).style.display = "block";
}
function hideAnswer( answerID ) {
document.getElementById('answer_'+answerID).style.display = "none";
}

function scrollWinners( winnerID ) {
document.getElementById('winners_'+winnerID).style.display = "block";
}
function hideWinners( winnerID ) {
document.getElementById('winners_'+winnerID).style.display = "none";
}

function clickBrowseFile(pic)
{
document.getElementById(pic).click();
}

var pic_input = 2;
function ViewNextPicInputs()
{
	if (pic_input < 5)
	{
		document.getElementById('pic_inputs-'+pic_input).style.display = "block";
		pic_input++;
	}
	else
	{
		document.getElementById('pic_inputs-5').style.display = "block";
		document.getElementById('morePictures').style.display = "none";
	}
}


var previewFields = new Array();

function showPreview( template ) {
	newwindow=window.open( '/templates/popup/'+template,'preview','height=500,width=520,scrollbars=yes');
	if (window.focus) {newwindow.focus()};
}


function performShow() {
	for( var i=0; previewFields[i]; i++ ) {
		var source = document.getElementById( previewFields[i] );
		if( source ) {
			var dest = newwindow.document.getElementById( previewFields[i]+"_add" );
			dest.innerHTML = source.value;
		}
	}
}



/* AJAX */


var actualLink;
var actualContainer;

function loadAjaxPage( linkURL, containerID ) {
	actualLink = linkURL;
	actualContainer = containerID;
	$.ajax({
		url: linkURL,
		success: function(msg){
			$("#"+containerID).html( msg );
		}
	});
}

function loadAjaxJSPage( linkURL, containerID ) {
	actualLink = linkURL;
	actualContainer = containerID;
	$.ajax({
		url: linkURL,
		dataType: "html",
		success: function(msg){
			if( msg.length > 0 ) {
				$("#"+containerID).html( msg );
			}
		}
	});
}


function countChars( elemID, max ) {
	var text = $("#"+elemID).val();
	var len = "0";
	if (text.length > 0){
		if (text.length > max && max > 0){
			var len = '<span style="color: red">'+text.length+'</span>';
		} else {
			var len = text.length;
		}
	} 
	$("#"+elemID+"-chars").html(len);
}

function checkUnique(table, field, name, edit){
	var elem = $("#"+field).val();
	loadAjaxPage('/ajax/check_unique.html?table='+table+'&field='+field+'&name='+name+'&elem='+elem+'&edit='+edit, field+'-unique_info');
}


function doPopup(pageName) {
	newwindow=window.open( '/popup/'+pageName+'.html','popup','height=525,width=691,scrollbars=yes');
	if (window.focus) {newwindow.focus()};
}

var showAdvanced = 0;

function changeAdvancedSearch() {
	if (showAdvanced == 0){
		$("#advance_search").css("display", "block");
		$('.basic_search').removeClass("width_max");
		$("#show_hide").html("Hide advanced search");
		showAdvanced = 1;
	} else {
		$("#advance_search").css("display", "none");
		$('.basic_search').addClass("width_max");
		$("#show_hide").html("Show advanced search");
		showAdvanced = 0;
	}
	$("#adv").val(showAdvanced);
}

function updateRangeBox(value) {
	$.ajax({
		type: "POST",
		url: "/ajax/show_search_results.html",
		data: "range="+value,
		success: function(msg){
			$("#ajax-search_results").html( msg );
			revindToResults();
		},
		failure: function(msg){
			alert("There was a problem with your search.");
		}
	});
}

function addToCart(item, quantity) {
	jQuery("#ajax-cartcont").hide();
	loadAjaxPage('/ajax/shopping_cart.html?add='+item+','+quantity, 'ajax-cartcont');
	$(document).scrollTo( "#ajax-cart", { duration:300, axis:'y' });
	jQuery("#ajax-cartcont").fadeIn( "slow" );
}

function addToPaymentCart(item, quantity) {
	$.ajax({
		url: '/ajax/payment_cart.html?add='+item+','+quantity,
		success: function(msg){
			$("#ajax-payment").html( msg );
			loadAjaxPage('/ajax/shopping_cart.html', '');
			loadAjaxPage('/ajax/total_price.html', 'ajax-price');
		}
	});
}

function removeFromPaymentCart(item, quantity) {
	$.ajax({
		url: '/ajax/payment_cart.html?remove='+item+','+quantity,
		success: function(msg){
			$("#ajax-payment").html( msg );
			loadAjaxPage('/ajax/shopping_cart.html', 'ajax-cart');
			loadAjaxPage('/ajax/total_price.html', 'ajax-price');
		}
	});
}

function updateDelivery(option) {
	if (option == undefined){
		option = defaultDelivery;
	}
	loadAjaxPage('/ajax/total_price.html?delivery='+option, 'ajax-price');
}

var showDelivery = 0;

function deliveryUpdate() {
	if (showDelivery == 0){
		$("#delivery_div").css("display", "block");
		document.getElementById('country').readOnly = false;
		showDelivery = 1;
	} else {
		document.getElementById('country').readOnly = true;
		updateDelivery();
		$("#delivery_div").css("display", "none");
		showDelivery = 0;
	}
}

function revindToResults() {
	$(document).scrollTo( "#ajax-search_results", { duration:300, axis:'y' });
	$("#ajax-search_results table").highlightFade( "silver" );
}

function revindToErrors () {
	$('#quick_payment_form input.submit, #payment_form .submit').click(function() {
		$("#ajax-form_submit").html('<img src="/ajax-loader.gif" />');
		document.location.href='#main';
		//$(document).scrollTo( "#ajax-form_submit", { duration:300, axis:'y' });
	});
}

function hideArrows () {
	if(typeof(countImages) != "undefined") {
	if(parseInt($('#images').css("marginTop")) == 231 * countImages * (-1)) {
		$('.image_left').hide();
	}
	
	if(parseInt($('#images').css("marginTop")) == 231 * countImages) {
		$('.image_right').hide();
	}

	
	if(countImages == -1) {
		$('.to_buy .bordered_box').hide();
	}
	}
}

$(document).ready(function() {
	revindToErrors();
	hideArrows();
});

function checkRange(range, opt_range){
	$(".ch_range").attr("checked", false);
	$("#range_"+range).attr("checked", true);
	if (opt_range > 0){
		$("#range_"+opt_range).attr("checked", true);
	}
	$("#basic_searchf").submit();
	revindToResults();
}

