var ObjectXMLHttp = "";

function ajaxConn() {
	// AJAX connection
	if (window.XMLHttpRequest){
		ObjectXMLHttp = new XMLHttpRequest(); 
		} else if (window.ActiveXObject){
		ObjectXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
}


//wysyłanie zapytania metodą POST


ajaxConn();

	//limit text in textarea
	function textCounter() {

    var field = document.getElementById('opis_f');
    var counter = document.getElementById('remChar');
    var maxlimit = 200;

		if(field.value.length > maxlimit) {
			field.value = field.value.substring(0, maxlimit);
		} else {
			counter.innerHTML = maxlimit - field.value.length;
		}
	
	}
	
	function sprawdzNIP( inputVal )
	{
		if ( !inputVal.match( /^[0-9]{3}-[0-9]{2}-[0-9]{2}-[0-9]{3}$/ ) )
		{
			return false;
		}
		return true;
	}

	function checkPass(inputVal){
		if ( !inputVal.match(/^[a-zA-Z0-9 ]+$/)){
			return false;
		}
		return true;
	}


	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 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 clearLabel(id){
	document.getElementById(id).innerHTML = '';
}



function verifyKrok2() {
var nazwa_f1 = document.getElementById('nazwa_f');
var imie1 = document.getElementById('imie');
var nazwisko1 = document.getElementById('nazwisko');
var nip1 = document.getElementById('nip');
var opis_f1 = document.getElementById('opis_f');
var lon = document.getElementById('lon');
var lat = document.getElementById('lat');
var search_label1 = document.getElementById('search_label');
var miasto_f1 = document.getElementById('miasto_f');
var kod_pocztowy1 = document.getElementById('kod_pocztowy');
var ulica1 = document.getElementById('ulica_f');
var tel_f1 = document.getElementById('tel_f');
var email1 = document.getElementById('email_f');
var haslo1 = document.getElementById('haslo');
var haslo_powt1 = document.getElementById('haslo_powt');
var haslo1_label = document.getElementById('haslo_label');
var haslo_powt1_label = document.getElementById('haslo_powt_label');
var dane_os1 = document.getElementById('dane_os');
var dane_os1_label = document.getElementById('dane_os_label');

	/* if (imie1.value.length == 0 || imie1.value == 'Proszę podać imię.'){
		imie1.value = 'Proszę podać imię.';
		imie1.style.color = 'red';
		imie1.style.fontWeight = 'bold';
		imie1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}

	if (nazwisko1.value.length == 0 || nazwisko1.value == 'Proszę podać nazwisko.') {
		nazwisko1.value = 'Proszę podać nazwisko.';
		nazwisko1.style.color = 'red';
		nazwisko1.style.fontWeight = 'bold';
		nazwisko1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		} */

	if (nazwa_f1.value.length == 0 || nazwa_f1.value == 'Proszę podać nazwę firmy.') {
		nazwa_f1.value = 'Proszę podać nazwę firmy.';
		nazwa_f1.style.color = 'red';
		nazwa_f1.style.fontWeight = 'bold';
		nazwa_f1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		} else {
			nazwa_f1.value = nazwa_f1.value.replace(/\"/gi, "&quot;");}
	
	/* if (nip1.value.length==0 || nip1.value.length>0 && !sprawdzNIP(nip1.value)){
		nip1.value = 'Błędny NIP';
		nip1.style.color = 'red';
		nip1.style.fontWeight = 'bold';
		nip1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}
		} */

	if (miasto_f1.value.length == 0 || miasto_f1.value == 'Proszę podać nazwę miasta.') {
		miasto_f1.value = 'Proszę podać nazwę miasta.';
		miasto_f1.style.color = 'red';
		miasto_f1.style.fontWeight = 'bold';
		miasto_f1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}
		
	if (ulica1.value.length == 0 || ulica1.value == 'Proszę podać nazwę ulicy oraz numer.') {
		ulica1.value = 'Proszę podać nazwę ulicy oraz numer.';
		ulica1.style.color = 'red';
		ulica1.style.fontWeight = 'bold';
		ulica1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}
		
	/* if (kod_pocztowy1.value.length == 0 || kod_pocztowy1.value == 'Proszę podać kod pocztowy.') {
		kod_pocztowy1.value = 'Proszę podać kod pocztowy.';
		kod_pocztowy1.style.color = 'red';
		kod_pocztowy1.style.fontWeight = 'bold';
		kod_pocztowy1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}

	if (tel_f1.value.length == 0 || tel_f1.value == 'Proszę podać numer telefonu.') {
		tel_f1.value = 'Proszę podać numer telefonu.';
		tel_f1.style.color = 'red';
		tel_f1.style.fontWeight = 'bold';
		tel_f1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}

	if (email1.value.length == 0 || email1.value == 'Proszę podać e-mail.') {
		email1.value = 'Proszę podać e-mail.';
		email1.style.color = 'red';
		email1.style.fontWeight = 'bold';
		email1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}

	if (!isValidEmail(email1.value)) {
		email1.value = 'Proszę podać prawidłowy e-mail.';
		email1.style.color = 'red';
		email1.style.fontWeight = 'bold';
		email1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}


	if (nazwa_f1.value.length == 0 || nazwa_f1.value == 'Proszę podać nazwę firmy.') {
		nazwa_f1.value = 'Proszę podać nazwę firmy.';
		nazwa_f1.style.color = 'red';
		nazwa_f1.style.fontWeight = 'bold';
		nazwa_f1.onclick = "this.value='';this.style.color='black';this.style.fontWeight='normal'";
		return false;
		}

		
	if (haslo1.value.length == 0) {
		haslo1_label.innerHTML = 'Proszę podać hasło.';
		haslo1_label.style.color = 'red';
		haslo1_label.style.fontWeight = 'bold';
		return false;
		}

	if (haslo1.value.length < 7) {
		haslo1_label.innerHTML = 'Hasło musi mieć min. 7 znaków.';
		haslo1_label.style.color = 'red';
		haslo1_label.style.fontWeight = 'bold';
		return false;
		}

	if (!checkPass(haslo1.value)) {
		haslo1_label.innerHTML = 'Hasło nie może zawierać polskich znaków.';
		haslo1_label.style.color = 'red';
		haslo1_label.style.fontWeight = 'bold';
		return false;
		}

	if (haslo_powt1.value.length == 0) {
		haslo_powt1_label.innerHTML = 'Proszę powtórzyć hasło.';
		haslo_powt1_label.style.color = 'red';
		haslo_powt1_label.style.fontWeight = 'bold';
		haslo_powt1.onclick = "this.value=''";
		return false;
		} else if (haslo_powt1.value != haslo1.value){
		haslo_powt1_label.innerHTML = 'Oba hasła muszą być identyczne.';
		haslo_powt1_label.style.color = 'red';
		haslo_powt1_label.style.fontWeight = 'bold';
		haslo_powt1.onclick = "this.value=''";
		return false;
		} */

	if (!dane_os1.checked) {
		dane_os1_label.innerHTML = 'Musisz wyrazić zgodę żeby kontynuować.';
		dane_os1_label.style.color = 'red';
		dane_os1_label.style.fontWeight = 'bold';
		return false;
		} else {
			dane_os1_label.innerHTML = ''
		}
		
	if (lon.value.length == 0 || lat.value.length == 0){
		search_label1.innerHTML = 'Proszę zaznaczyć na mapie lokalizację.';
		search_label1.style.color = 'red';
		search_label1.style.fontWeight = 'bold';
		return false;
		} else {
			search_label1.innerHTML = '';
		} 
		
	return true;
}



function swapKrok2() {
	if(verifyKrok2()) {
		clearLabel('search_label');
		document.getElementById('krok2').style.display='none';
		document.getElementById('krok2right').style.display='none';
		document.getElementById('krok3').style.display='block';
		swapMapControls();
		swapLocationIcon();
		printConfirmation();
		}
}

function swapKrok3to2(){
		document.getElementById('krok2').style.display='block';
		document.getElementById('krok2right').style.display='block';
		document.getElementById('krok3').style.display='none';
		swapMapControls();
		swapLocationIcon();
}

function swapLocationIcon() {
	var parent = document.getElementById('surf1');
	var childMarkIcon = parent.childNodes;
	var currMarkIconID = childMarkIcon[2].id;
	var currMarkIconStyle = document.getElementById(currMarkIconID).style;

	if (currMarkIconStyle.visibility == 'visible') {
			currMarkIconStyle.visibility = 'hidden';
			} else {
			currMarkIconStyle.visibility = 'visible';
			}
}

function swapMapControls() {
	var mapToolbar = document.getElementById('_mapgo_toolbar').style;
	if (mapToolbar.visibility == 'hidden') {
		mapToolbar.visibility = 'visible';
		} else {
		mapToolbar.visibility = 'hidden';
		}

}

function swapLayers(layer1,layer2){
	document.getElementById(layer1).style.display="none";
	document.getElementById(layer2).style.display="block";
}


function printConfirmation(){
var imie1 = document.getElementById('imie').value;
var nazwisko1 = document.getElementById('nazwisko').value;
var nazwa_f1 = document.getElementById('nazwa_f').value;
var nip1 = document.getElementById('nip').value;
var opis_f1 = document.getElementById('opis_f').value;
var lon = document.getElementById('lon').value;
var lat = document.getElementById('lat').value;
var search_label1 = document.getElementById('search_label').value;
var miasto_f1 = document.getElementById('miasto_f').value;
var kod_pocztowy1 = document.getElementById('kod_pocztowy').value;
var ulica_f1 = document.getElementById('ulica_f').value;
var fax_f1 = document.getElementById('fax_f').value;
var tel_f1 = document.getElementById('tel_f').value;
var tel_kom_f1 = document.getElementById('tel_kom_f').value;
var email_f1 = document.getElementById('email_f').value;
var www_f1 = document.getElementById('www_f').value;
/* var zdjecie_f1 = document.getElementById('zdjecie_f').value; */

var confirmation_content = '<table><tr><td class="rightalign"><strong>Imię: </strong></td><td>'+imie1+'</td></tr><tr><td class="rightalign"><strong>Nazwisko: </strong></td><td>'+nazwisko1+'</td></tr><tr><td class="rightalign"><strong>Nazwa firmy: </strong></td><td>'+nazwa_f1+'</td></tr><tr><td class="rightalign"><strong>Miasto: </strong></td><td>'+miasto_f1+'</td></tr><tr><td class="rightalign"><strong>Ulica: </strong></td><td>'+ulica_f1+'</td></tr><tr><tr><td class="rightalign"><strong>Kod pocztowy: </strong></td><td>'+kod_pocztowy1+'</td></tr><tr><td class="rightalign"><strong>Telefon: </strong></td><td>'+tel_f1+'</td></tr><tr><td class="rightalign"><strong>Telefon komórkowy: </strong></td><td>'+tel_kom_f1+'</td></tr><tr><td class="rightalign"><strong>Faks: </strong></td><td>'+fax_f1+'</td></tr><tr><td class="rightalign"><strong>E-mail: </strong></td><td>'+email_f1+'</td></tr><tr><td class="rightalign"><strong>WWW: </strong></td><td>'+www_f1+'</td></tr><tr><td class="rightalign"><strong>NIP: </strong></td><td>'+nip1+'</td></tr><tr><td class="rightalign"><strong>Opis: </strong></td><td>'+opis_f1+'</td></tr></table>';

//<tr><td class="rightalign"><strong>Zdjęcie: </strong></td><td>'+zdjecie_f1+'</td></tr>

document.getElementById('confirmation').innerHTML = confirmation_content;

}

function sendMapgoCard(){
	var imie1 = document.getElementById('imie').value;
	var nazwisko1 = document.getElementById('nazwisko').value;
	var nazwa_f1 = document.getElementById('nazwa_f').value.replace(/&quot;/g,'').replace(/'/g,'');
	var nip1 = document.getElementById('nip').value;
	var opis_f1 = document.getElementById('opis_f').value;
	var lon = document.getElementById('lon').value;
	var lat = document.getElementById('lat').value;
	var search_label1 = document.getElementById('search_label').value;
	var miasto_f1 = document.getElementById('miasto_f').value;
	var kod_pocztowy1 = document.getElementById('kod_pocztowy').value;
	var ulica_f1 = document.getElementById('ulica_f').value;
	var fax_f1 = document.getElementById('fax_f').value;
	var tel_f1 = document.getElementById('tel_f').value;
	var tel_kom_f1 = document.getElementById('tel_kom_f').value;
	var email_f1 = document.getElementById('email_f').value;
	var www_f1 = document.getElementById('www_f').value;
	var mapgoCard = {
			"imie":imie1,
			"nazwisko":nazwisko1,
			"firma":nazwa_f1,
			"miasto":miasto_f1,
			"ulica":ulica_f1,
			"kod":kod_pocztowy1,
			"tel":tel_f1,
			"telkom":tel_kom_f1,
			"fax":fax_f1,
			"mail":email_f1,
			"www":www_f1,
			"nip":nip1,
			"opis":opis_f1,
			"lon":lon,
			"lat":lat
			}

		var mapgoCardString = JSON.stringify(mapgoCard);
			if(ObjectXMLHttp){
				var url = "../mapgowizytowka/wizFileCreate.php";
				var params = "data="+mapgoCardString;
				ObjectXMLHttp.open("POST",url);
				//Send the proper header information along with the request
				ObjectXMLHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				ObjectXMLHttp.setRequestHeader("Content-length", params.length);
				ObjectXMLHttp.setRequestHeader("Connection", "close");


				ObjectXMLHttp.onreadystatechange = function(){
				if (ObjectXMLHttp.readyState < 4){

				} else
				 if (ObjectXMLHttp.readyState == 4 && ObjectXMLHttp.status == 200){

					var ajax_resp=ObjectXMLHttp.responseText;
					var ajax_resp_obj = JSON.parse(ajax_resp);
					var status = ajax_resp_obj.status;
					var link = ajax_resp_obj.link;
					var firma = ajax_resp_obj.firma;
					var cardurl = 'http://api.mapgo.pl/mapgowizytowka/' + link + '/';
					if (status == 0){
						var answer = '<h1>Dziękujemy za skorzystanie z naszych usług.</h1><p>Twoja Wizytówka mapGO dostępna jest pod adresem <a href="' + cardurl + '" target="_blank">' + cardurl + '</a></p><p>Żeby wstawić odnośnik do Twojej Wizytówki mapGO na inną stronę, skopiuj poniższy kod:</p><p><textarea class="pre"><a href="' + cardurl + '" Wizytówka mapGO :: ' + firma + '</a></textarea></p>';
						document.getElementById('krok3').style.display = "none";
						var answer_box = document.getElementById('answer_box');
						answer_box.style.display = 'block';
						answer_box.innerHTML = answer;
					} else {
						var answer = "Wizytówka o identyfikatorze" + status + " już istnieje! Spróbuj jeszcze raz!"
						var answer_box = document.getElementById('answer_box');
						answer_box.style.display = 'block';
						answer_box.innerHTML = answer;
					}
				   }
				}

			ObjectXMLHttp.send(params);

			}
}

//wyszukiwanie obiektów po nazwach tagów
function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

//wyszukiwanie obiektów po klasie
function getElementsByClass(searchClass,node,tag) {
        var classElements = new Array();
        if ( node == null )
                node = document;
        if ( tag == null )
                tag = '*';
        var els = node.getElementsByTagName(tag);
        var elsLen = els.length;
        var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
        for (i = 0, j = 0; i < elsLen; i++) {
                if ( pattern.test(els[i].className) ) {
                        classElements[j] = els[i];
                        j++;
                }
        }
        return classElements;
}


function toggleMapControls(currid){
	var controlbox = document.getElementById('controls');
	var controls = getElementsByTagNames('img',controlbox);
	for (i=0;i<controls.length;i++){
		var rawsource = controls[i].src;
		var state = rawsource.indexOf("_on.");
		controls[i].src = rawsource.replace(/\_on\.png/gi,".png");
	}
	var img = document.getElementById(currid);
	var src = img.src;
	img.src = src.replace(/\.png/gi,"_on.png");
}
