function check_uname_availability(theName){
	$.post("/data/ajax/check_registration.ajax",
		{ uname: theName },
		function(data){
			$("#uname_availability").html( data );
	});
}
function check_email_availability(theName){
	$.post("/data/ajax/check_registration.ajax",
		{ email: theName },
		function(data){
			$("#email_availability").html( data );
	});
}
function check_passwords(){
	if( $('#m_pass').val() != $('#m_pass2').val() )
		$("#pass_compare").html( "<span class=\"brightred\">Wachtwoorden komen niet overeen</span>" );
	else
		$("#pass_compare").html( "&nbsp;" );
}

var activeTags = new Array(0);
function tagCatClick(ptcId){
	$("#tag_tags").html('<p align="center"><img src="http://monweb01.montay.nl/images/ajax-loader.gif" class="noline"></p>');
	$.post("/data/ajax/do_upload_tagclick.ajax",{ catId: ptcId },
		function(data){
			temp = data.split('|');
			$("#tag_cats").html( temp[0] );
			$("#tag_tags").html( temp[1] );

			for(i = 0; i < activeTags.length; i++){
				if(document.getElementById(activeTags[i]))
					document.getElementById(activeTags[i]).checked = true;
			}
//			alert( activeTags.join('-') );
		}
	);
}
function tagClick(ptId){
	if(document.getElementById(ptId).checked)
		activeTags.push(ptId);
	else{
		for (key in activeTags){
			if(activeTags[key] == ptId)
				activeTags.splice(key,1);
		}
//		remId = activeTags.indexOf(ptId);
//		alert(remId);
	}

//	alert(activeTags.join('-'));
/*	selBox = document.getElementById('selectedTags');
	arrTexts = new Array();

	for(i=0; i<selBox.length; i++)  {
			arrVal = selBox.options[i].value;
			arrTexts.push(selBox.options[i].value);
	}
	var elOptNew = document.createElement('option');

				//in_array is defined in montay_webarchitects.js
	if(!arrTexts.in_array(ptId)){
		elOptNew.text = ptNm;
		elOptNew.value = ptId;
		
		try {
			selBox.add(elOptNew, null); // standards compliant; doesn't work in IE
		} catch(ex) {
			selBox.add(elOptNew); // IE only
		}
	}
	sortOptions(selBox);*/
}

function addTag(catId,tagName){
	if(tagName.length > 2){
		$.post("/data/ajax/do_upload_tagclick.ajax",{ newTag: tagName, parentId: catId },
			function(data){
				newtagId = data;
				tagCatClick(catId);
				tagClick(newtagId);
		});
	}else{
		alert('Vul een zoekwoord in wat u mist in deze categorie, maar wat wel bij uw foto past');
	}
//	alert(catId+'-'+tagName);
}

function compareOptionText(a,b) {	//used by sorting function below
/*	return >0 if a>b
			0 if a=b
			<0 if a<b	*/
	return a.text!=b.text ? a.text < b.text ? -1 : 1 : 0;
}

function sortOptions(list) {
	var items = list.options.length;
	// create array and make copies of options in list
	var tmpArray = new Array(items);
	for ( i=0; i<items; i++ )
		tmpArray[i] = new Option(list.options[i].text,list.options[i].value);
  // sort options using given function
	tmpArray.sort(compareOptionText);
  // make copies of sorted options back to list
	for ( i=0; i<items; i++ )
		list.options[i] = new Option(tmpArray[i].text,tmpArray[i].value);
}

/*function center_map_on_ip(){
	$.post("/data/ajax/getgeofromip.ajax.php",
		{ valid: true },
		function(data){
			temp = data.split('|');
			var glatlng = new GLatLng(temp[0],temp[1]);
			map.setCenter(glatlng, 12);
		}
	);
}*/

this.imagePreview = function(){	
	/* CONFIG */
		
		xOffset = -15;
		yOffset = -205;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
		
	/* END CONFIG */
	$("a.preview").hover(function(e){
		this.t = this.title;
		this.title = "";	
		var c = (this.t != "") ? "<br/>" + this.t : "";
		var url = this.href.split('/');
//		alert(url[5]);
		$("body").append("<p id='preview'><img src='/show_img/"+ url[5] +"/preview.jpg' alt='Image preview' />"+ c +"</p>");								 
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		this.title = this.t;	
		$("#preview").remove();
    });	
	$("a.preview").mousemove(function(e){
		$("#preview")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};


// starting the script on page load
$(document).ready(function(){
	imagePreview();

	$.get("/data/ajax/token.ajax",function(txt){
		$(".securedForm").append('<input type="hidden" name="ts" value="'+txt+'" />');
	});

// Tabs
	$('#tabs').tabs();
	$('#tabStap1').text('Stap 1');
	$('#tabStap2').text('Stap 2');
	$('#tabStap3').text('Stap 2');
	$('#tabStap4').text('Stap 3');
	$("#pDate").datepicker();

	$(".spinBtn").SpinButton({
		min: 1,						// Set lower limit.
		max: 2500					// Set upper limit.
	});

	$('#orderTabs').tabs();

	function updateBar(){
		var val = $("#progressbar").progressbar('option','value');
		if(val < 100){
			val += 0.1;
			$("#progressbar").progressbar('option','value',val );
			setTimeout(function() { updateBar(); },500);
		}
	}
//	updateBar();
//	for(i=1;i<100;i++)
//		setTimeout("updateBar()",1000);



/*	$('#tabs').bind('tabsshow', function(event, ui) {
		if (ui.panel.id == "tabs-3") {
			resizeMap();
		}
	});*/
	$('.uploadTabs').data('disabled.tabs', [1, 2, 3]);	// tabs start with 0 // 

	$('#nextBtn1').click( function(){
		map.checkResize();
		map.panTo(map.getCenter());
		setTimeout("map.checkResize()",75);
		setTimeout("map.returnToSavedPosition()",250);
		$('.uploadTabs').tabs('enable',1);
		$('.uploadTabs').tabs('select',1);
	});
	$('#prevBtn2').click( function(){
		$('.uploadTabs').tabs('select',0);
	});
	$('#nextBtn2').click( function(){
		var criteriaAnswers = new Array();						   
		for (var i = 0; i < 9999; i++){			// todo: get exact question ids from db by ajax request
			if(document.forms['foto_form'].elements['c_criteria_'+i]){
				var radioList = document.getElementsByName('c_criteria_'+i);
				for( var j=0; j < radioList.length; ++j){
					if( radioList[j].checked){
						criteriaAnswers[i] = i + '|' + radioList[j].value;
					}
				}
			}
		}
		criteriaAnswers = criteriaAnswers.join('#');
		
		$.post("/data/ajax/check_upload_criteria.ajax",
			{ criteria: criteriaAnswers },
			function(data){
				temp = data.split('|');
				if(temp[0] == 'error'){
					$("#step2errMsg").html( temp[1] );
					$("#step2errMsg").show();
					window.location = '#top';
				}else{
					$("#step2errMsg").hide();
					$('.step2radio').attr('disabled','disabled');
					$('.uploadTabs').tabs('enable',2);
					$('.uploadTabs').tabs('select',2);
					$('#latlongBtn').click();
				}
		});
		
	});

	$('#nextBtn3').click( function(){
		$.post("/data/ajax/check_upload_postdetails.ajax",
			{
				lat: $('#lat').val(),
				long: $('#long').val(),
				loc: $('#loc').val(),
				location: $('#pLocation').val(),
				date: $('#pDate').val(),
				name: $('#pName').val(),
				desc: $('#pDesc').val(),
				baseprice: $('#pBasePrice').val()
			},
			function(data){
				temp = data.split('|');
				if(temp.length == 3){
					baseprice: $('#pBasePrice').val(temp[2]);
				}
				if(temp[0] == 'error'){
					$("#step3errMsg").html( temp[1] );
					$("#step3errMsg").show();
					window.location = '#top';
				}else{
					$("#step3errMsg").hide();
					
					$('#lat').attr('disabled','disabled');
					$('#long').attr('disabled','disabled');
					$('#loc').attr('disabled','disabled');
					$('#pLocation').attr('disabled','disabled');
					$('#pDate').attr('disabled','disabled');
					$('#pName').attr('disabled','disabled');
					$('#pDesc').attr('disabled','disabled');
					$('#pBasePrice').attr('disabled','disabled');
					
					$('.uploadTabs').tabs('enable',2);
					$('.uploadTabs').tabs('select',2);
				}
		});
	});
	$('#prevBtn3').click( function(){
		$('.uploadTabs').tabs('select',1);
	});
	$('#nextBtn4').click( function(){
/*		selBox = document.getElementsByName('tags');
		selOpts = new Array();
		for(i=0; i<selBox.length; i++)  {
			selOpts.push(selBox.options[i].value);
		}
		if(selOpts.length > 0)
			tags = selOpts.join('#');
		else
			tags = '';*/
		$('#hiddenTags').val(activeTags.join('#'));
		$.post("/data/ajax/check_upload_postdetails.ajax",
			{
				mainCat: $('#pMaincat').val(),
				tag_ids: activeTags.join('#')
			},
			function(data){
				temp = data.split('|');
				if(temp[0] == 'error'){
					$("#step4errMsg").html( temp[1] );
					$("#step4errMsg").show();
					window.location = '#top';
				}else{
					$("#step4errMsg").hide();
//					alert(data);
					$("*").removeAttr('disabled');
					document.getElementById('foto_form').submit();
				}
		});
	});
	$('#prevBtn4').click( function(){
		$('.uploadTabs').tabs('select',2);
	});

	$('#latlongBtn').click( function(){
		var lat = document.getElementById('lat').value;
		var lng = document.getElementById('long').value;
		map.checkResize();
		if(!isNaN(parseFloat(lat)) && !isNaN(parseFloat(lng))){
			var glatlng = new GLatLng(lat,lng);
			map.panTo(glatlng);
//			$('#nextBtn3').removeAttr('disabled');
		}
	});
	$('#locBtn').click( function(){
		setTimeout("searchAddress('loc')",750);
	});

/*	$('.tag_catDiv').click( function(){
//		alert($(this).attr('id'));
	});*/

	var button = $('#uplFileBtn'), interval;
	new AjaxUpload(button,{	// was Ajax_upload
		action: '/data/uploader.php', 
		name: 'userfile',
		onSubmit : function(file, ext){
			// change button text, when user selects file			
			button.val('Versturen...');
			$('#uplFileBtn').attr('disabled','disabled');
			$('#uplFileStatus').html('<br>Uw foto wordt verstuurd.<br>Een ogenblik geduld a.u.b.<br><div id="progressbar"></div>');
			$("#progressbar").progressbar();

			// allow uploading only 1 file at a time
			this.disable();
			
			// Uploding -> Uploading. -> Uploading...
			interval = window.setInterval(function(){
				var text = button.val();
				var val = $("#progressbar").progressbar('option','value');
				if(val < 100)
					val += 1;
				else
					val = 0;
				$("#progressbar").progressbar('option','value',val );

				if (text.length < 8){
					button.val(text + '.');					
				} else {
					button.val('Bezig');				
				}
			}, 200);
		},
		onComplete: function(file, response){
			button.val('Verstuurd');
//			alert(response);
			window.clearInterval(interval);
						
			// add file to the list
			$('#uplFileName').val(file);
			var temp = new Array();
			temp = response.split('|');
			if(temp[0] == 'error'){
				$('#uplFileStatus').html('Er ging iets mis bij het uploaden:<br>'+ temp[1]);
				this.enable();
				$('#uplFileBtn').removeAttr('disabled');
			}else{
				$('#hiddenFile').val(temp[1]);
				$('.smallStepImg').html('<img src="/show_img/pending/thumb/'+ temp[1] +'" align="left"><br>' );
				$('#step2img').html('<center><img src="/show_img/pending/'+ temp[1] +'" align="left"></center>' );
				$('#nextBtn1').removeAttr('disabled');

				map.addOverlay(uploadMarker);
				map.checkResize();

				if(temp.length > 2 && temp[2].indexOf('#') > 0){	// gps coordinates in exif-data
//					alert(temp);
					ltlng = temp[2].split('#');
					$('#lat').val(ltlng[0]);
					$('#long').val(ltlng[1]);
					var glatlng = new GLatLng(ltlng[0],ltlng[1]);
					map.setCenter(glatlng, 9);
					map.panTo(glatlng);
					geocoder.getLocations(glatlng, _writeAddress);

					setTimeout("$('#latlongBtn').click();",1000);
					uploadMarker.setLatLng(glatlng);
				}else{
					$.post("/data/ajax/getmemberaddress.ajax",
						function(data){
							geocoder = new GClientGeocoder();
							geocoder.getLatLng(data, function(latlng) { 
								if (latlng && document.getElementById('map') != undefined){
//									alert(latlng);
									map.setCenter(latlng, 9);
									map.panTo(latlng);
									uploadMarker.setLatLng(latlng);
								}
							});
						});
				}
				if(temp.length == 4 && temp[3].indexOf('-') > 0){
					$('#pDate').val(temp[3]);
				}
			}
		}
	});
	

	function _writeAddress(response) {
		if (!response || response.Status.code != 200) {
	//		alert("Status Code:" + response.Status.code);
			document.getElementById('pLocation').value = '';
		} else {
			place = response.Placemark[0];
			document.getElementById('pLocation').value = place.address;
		}
	}

	
	$('#creditsToBuy').click( function(){
		$.post("/data/ajax/getcreditprices.ajax",
		{
			num: $('#creditsToBuy').val()
		},
		function(data){
			temp = data.split('|');
			$("#creditsPrice").html( temp[0] );
			$("#creditsTransCosts").html( temp[1] );
			$("#creditsSave").html( temp[2] );
			$("#creditsTotal").html( temp[3] );
			$("#creditsSaveMore").html( temp[4] );
		});
		$('#spacer').focus();
	});
	$('#creditsToBuy').change( function(){
		$('#creditsToBuy').click();
	});
	$('#creditsToBuy').click();
	
});

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function addUnLoadEvent(func) {
	var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {
	  window.onunload = func;
	} else {
	  window.onunload = function() {
	    oldonunload();
	    func();
	  }
	}
}
function GET(vari){
	URI = document.location.href;
	URI2 = URI.split("?");
	if(URI2[1]){
		URI3 = URI2[1].split("&");
		for(i=0;i < URI3.length; i++){
			URI4 = URI3[i].split("=");
			if(URI4[0] == vari){
				return URI4[1]
			}else{
				return false;
			}
		}
	}else
		return false;
}

