/////////////////////////////////////////////////////////////
//                                 _                     
//   _ __    ___    __ _   _   _  (_)  _ __    ___   ___ 
//  | '__|  / _ \  / _` | | | | | | | | '__|  / _ \ / __|
//  | |    |  __/ | (_| | | |_| | | | | |    |  __/ \__ \
//  |_|     \___|  \__, |  \__,_| |_| |_|     \___| |___/
//                    |_|                                
/////////////////////////////////////////////////////////////

dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.Tooltip");
dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.Form");
dojo.require("dijit.TitlePane");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Textarea");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.form.RadioButton");
dojo.require("dijit.form.CheckBox");
dojo.require("dojox.validate.regexp");
dojo.require("dijit.layout.StackContainer");
dojo.require("dijit.layout.BorderContainer");



/////////////////////////////////////////////////////////////
//                   _                       _ 
//    ___    _ __   | |   ___     __ _    __| |
//   / _ \  | '_ \  | |  / _ \   / _` |  / _` |
//  | (_) | | | | | | | | (_) | | (_| | | (_| |
//   \___/  |_| |_| |_|  \___/   \__,_|  \__,_|
/////////////////////////////////////////////////////////////

	
// dojo.addOnLoad(function(){
// 	ihcc.geocoder = new GClientGeocoder();
// 	ihcc.sendLocation();
// });




////////////////////////////
//    ___    _ __   __/\__
//   / _ \  | '_ \  \    /
//  | (_) | | | | | /_  _\
//   \___/  |_| |_|   \/  
////////////////////////////
                  

//////////////////////////////////////////////////////////////////
//   _   _                                                    
//  (_) | |__     ___    ___      __   __   __ _   _ __   ___ 
//  | | | '_ \   / __|  / __|     \ \ / /  / _` | | '__| / __|
//  | | | | | | | (__  | (__   _   \ V /  | (_| | | |    \__ \
//  |_| |_| |_|  \___|  \___| (_)   \_/    \__,_| |_|    |___/
//////////////////////////////////////////////////////////////////
var ihcc = {};
var IHCC = {};
IHCC.loadHTML = function(url, node) {};

djConfig['isDebug'] = false;

ihcc.markerSelectionPrefix = {
	1: "/media/img/pflege_ambulant",
	2: "/media/img/pflege_stationaer",
	3: "/media/img/medizintechnik",
	4: "/media/img/klinik",
	5: "/media/img/therapie"
};

ihcc.formConstants = {
	USERNAME_GONE: "Dieser Username ist bereits vergeben"
}

ihcc.markerSelectionSuffix = {
	0: "_belegt.png",
	1: ".png"
};

ihcc.geocoder = null;

ihcc.markerPool = [];

ihcc.markerSelection = {};

ihcc.filterState = {
	stapfl:true,
	ambpfl:true,
	klinik:true,
	medtec:true,
	therapy:true,
	adults:true,
	children:true,
	capacity:true	
};
	
ihcc.numLocations = 1;
	
ihcc.geocoder = null;

////////////////////////////////////////////////////////////////////////////////////////////
//   _   _                          __                          _     _                       
//  (_) | |__     ___    ___       / _|  _   _   _ __     ___  | |_  (_)   ___    _ __    ___ 
//  | | | '_ \   / __|  / __|     | |_  | | | | | '_ \   / __| | __| | |  / _ \  | '_ \  / __|
//  | | | | | | | (__  | (__   _  |  _| | |_| | | | | | | (__  | |_  | | | (_) | | | | | \__ \
//  |_| |_| |_|  \___|  \___| (_) |_|    \__,_| |_| |_|  \___|  \__| |_|  \___/  |_| |_| |___/
////////////////////////////////////////////////////////////////////////////////////////////


ihcc.dependentServices = function(sectorField)
{
    
    if (sectorField.getValue())
    {
        //alert(sectorField.getValue());
        
        idSelect = sectorField.id.substring(0, sectorField.id.indexOf("-")) + "-services";
        
        idLoc = sectorField.id.substring(sectorField.id.indexOf("id_")+3, sectorField.id.indexOf("_location"));
        if (idLoc == "NEW") idLoc = 0;
            
        services = dijit.byId(idSelect);
        
        //alert(services.domNode.innerHTML);
        dojo.xhrGet({
            url:"/registrierung/live-service-list/"+sectorField.getValue()+"/"+idLoc+"/",
            handlesAs: "text",
            load: function(data,args){
                services.domNode.innerHTML = data;
            }
        });
    }
};

ihcc.async_ensureUsernameUniqueness = function(usernameField) {
	var val = usernameField.attr("value");
	if( val.match(/\w{3,100}/) ) {
		dojo.xhrGet({
			url:"/registrierung/live-username-available/"+escape(val)+"/",
			handleAs: "text",
			load:function(data,args) {
				if(data!="true") {
					usernameField.attr("value", ihcc.formConstants.USERNAME_GONE);
				}
			}
		});
	}
};

ihcc.filterMarkers = function() {
	var st=ihcc.filterState;
	dojo.forEach(ihcc.markerPool, function(m) {
		if( (	(st.stapfl && m.sector==2)
			 || (st.ambpfl && m.sector==1)
			 || (st.klinik && m.sector==4)
			 || (st.therapy && m.sector==5)
			 || (st.medtec && m.sector==3) )
		  &&(	(st.adults && m.adults) 
			 ||	(st.children && m.children) )
		  &&(st.capacity || m.capacity)
		) m.marker.show();
		else m.marker.hide();
	});
};
	
ihcc.finalConfirm = function() {
	var button = dijit.byId("next_step");
	var dialogCloseBtn = dijit.byId("closeDialog");
	var confirmDialog = dijit.byId("confirmDialog");

	dojo.connect(button, "onClick", function(event) {
		//Stop the submit event since we want to control form submission.
		event.preventDefault();
		event.stopPropagation();
		
		//The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
		//Note that there isn't a url passed.  xhrPost will extract the url to call from the form's
		//'action' attribute.  You could also leave off the action attribute and set the url of the xhrPost object
		//either should work.
		var xhrArgs = {
			url: "/registrierung/live-confirm/",
			postData: "confirmed",
			handleAs: "text",
			load: function(data){
				dijit.byId("confirmDialog").show();
			}
		}
		//Call the asynchronous xhrPost
		var deferred = dojo.xhrPost(xhrArgs);
	});
	
	dojo.connect(dialogCloseBtn, "onClick", function(event) {
		confirmDialog.hide();
	});
	
	dojo.connect(confirmDialog, "hide", function(event) {
		window.location.href = "/";
	});
};

ihcc.fireGetCoords = function() {};

ihcc.getCoordsFailed = function (relatedForm) {
    dojo.byId("transfer_"+relatedForm.id.substring(3)).innerHTML="";
    dijit.byId("geoLocFailed").show();
};

ihcc.getCoords = function(relatedForm, onSuccessFnct, onSuccessFnctArgs) {
	console.log("calling getCoords");
	var l_address = dijit.byId(relatedForm.id+"-address").getValue();
	var l_zipcode = dijit.byId(relatedForm.id+"-zipcode").getValue();
	var l_city = dijit.byId(relatedForm.id+"-city").getValue();
	var loc = l_address + " " + l_zipcode + " " + l_city + " Deutschland";
	ihcc.geocoder.getLatLng(
		loc,
		function(point) {
			if (!point) {
				if (navigator.appName == "Netscape") {
					console.log(loc + " not found");
				}
                ihcc.getCoordsFailed(relatedForm);
			} else {
				var point_wkt = "POINT ("+point.lat()+" "+point.lng()+")";
				dijit.byId(relatedForm.id+"-coords").setValue(point_wkt);
				var deferred = onSuccessFnct(onSuccessFnctArgs);
			}
		}
	)
};

ihcc._getCoords = function(l_address, l_zipcode, l_city, onSuccessFnct, onSuccessFnctArgs) {
	var loc = l_address + " " + l_zipcode + " " + l_city + " Deutschland";

};

ihcc.gotoAddress = function() {
	var address = dijit.byId("masterSearchBox").getValue();
	if (address !== "") {
		ihcc.setCenterToAddress(address);
	}
};

ihcc.mapAddress = function(lat, lng, markerKind, markup, capacity, adults, children, sector) {
	point = new GLatLng(parseFloat(lat),
						parseFloat(lng));
	var marker = new GMarker(point, markerKind);
	ihcc.map.addOverlay(marker);
	//console.log(marker + ", " + capacity + ", " + adults + ", " + children + ", " + sector);
	var markerRef = { marker: marker, capacity: capacity, adults: adults, children: children, sector: sector };
	//console.log(markerRef);
	ihcc.markerPool.push(markerRef);
	marker.bindInfoWindowHtml(markup);
};

ihcc.nextStep = function() {
	window.location.href='/registrierung/bestaetigung/';
};

ihcc.openRequestInviteDialog = function() {
	dijit.byId("demoDialog").hide();
	dijit.byId("preActivationDialog").show();
};

// ihcc.sendLocation = function() {
// 	var button = dijit.byId("paRegister");
// 	
// 	dojo.connect(button, "onClick", function(event) {
// 		//Stop the submit event since we want to control form submission.
// 		event.preventDefault();
// 		event.stopPropagation();
// 		if ( dijit.byId("preActivationForm").isValid() ) {
// 			//The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
// 			//Note that there isn't a url passed.  xhrPost will extract the url to call from the form's
// 			//'action' attribute.  You could also leave off the action attribute and set the url of the xhrPost object
// 			//either should work.
// 			var xhrArgs = {
// 				form: dojo.byId("preActivationForm"),
// 				handleAs: "text",
// 				load: function(data){
// 					dijit.byId("preActivationDialog").hide();
// 					window.location.reload()
// 				}
// 			}
// 			//Call the asynchronous xhrPost
// 			dojo.byId("transfer").innerHTML = "Wird übertragen...";
// 			ihcc.getCoords(dojo.xhrPost, xhrArgs);
// 			//var deferred = dojo.xhrPost(xhrArgs);
// 		};
// 	});
// };

ihcc.sendLocation = function(connectedButton, connectedForm, loadFnct) {
	// send the location to the server
	// this gets all the necessary data from the provided form, calls
	// ihcc.getCoords and sends the results to the server
	// use inside an addOnLoad
	// @conntectedButton: the dijit.form.Button instance to connect to
	// @connectedForm: the form instance to connect to; use dojo.byId to get
	// @loadFnct: the function to pass to the load handler
	console.log("start da sendLocation");
	console.log(connectedButton);
	console.log(connectedForm);
	console.log(loadFnct);
	
	dojo.connect(connectedButton, "onClick", function(event) {
		//Stop the submit event since we want to control form submission.
		console.log("start da connect");
		
		event.preventDefault();
		event.stopPropagation();
		//The parameters to pass to xhrPost, the form, how to handle it, and the callbacks.
		//Note that there isn't a url passed.  xhrPost will extract the url to call from the form's
		//'action' attribute.  You could also leave off the action attribute and set the url of the xhrPost object
		//either should work.
		var xhrArgs = {
			form: connectedForm,
			handleAs: "text",
			load: loadFnct
			// load: function(data){
			// 	window.location.href='/registrierung/standorte/';
			// }
		}
		//Call the asynchronous xhrPost
		dojo.byId("transfer_"+connectedForm.id.substring(3)).innerHTML = "<img src='/media/img/spinner.gif' /> Wird übertragen...";
		ihcc.getCoords(connectedForm, dojo.xhrPost, xhrArgs);
		//var deferred = dojo.xhrPost(xhrArgs);
	});
};

ihcc.setCenterToAddress = function(address) {
	var search_address = address + " Deutschland";
	var zoom = 12;
	ihcc.geocoder.getLatLng(
		search_address,
		function(point) {
			if (!point) {
				alert(address + " not found");
				if (navigator.appName == "Netscape") {
					console.log(search_address + " not found");
				}
			} else {
				ihcc.map.setCenter(point, zoom);
				ihcc.map.setMapType(G_NORMAL_MAP);
			}
		}
	)
};

ihcc.setCenterToRegion = function(region) {
	var region_data = {
		'de': {lat: 51.165691, lng: 10.451526, zoom: 6},
		'bw': {lat: 48.6616037, lng: 9.3501336, zoom: 7},
		'by': {lat: 48.7904472, lng: 11.4978895, zoom: 7},
		'be': {lat: 52.4938053, lng: 13.4552919, zoom: 10},
		'bb': {lat: 52.1313922, lng: 13.2162494, zoom: 8},
		'hb': {lat: 53.1333812, lng: 8.7584767, zoom: 10},
		'hh': {lat: 53.5363318, lng: 9.9945216, zoom: 10},
		'he': {lat: 50.6520515, lng: 9.1624376, zoom: 7},
		'mv': {lat: 53.6126505, lng: 12.4295953, zoom: 8},
		'ni': {lat: 52.6367036, lng: 9.8450765, zoom: 8},
		'nw': {lat: 51.4332367, lng: 7.6615938, zoom: 8},
		'rp': {lat: 50.118346, lng: 7.3089527, zoom: 8},
		'sl': {lat: 49.3964234, lng: 7.0229607, zoom: 9},
		'sn': {lat: 51.1045407, lng: 13.2017384, zoom: 8},
		'st': {lat: 51.9502649, lng: 11.6922735, zoom: 8},
		'sh': {lat: 54.2193672, lng: 9.6961167, zoom: 8},
		'th': {lat: 51.0109892, lng: 10.845346, zoom: 8}
	}
	point = new GLatLng(parseFloat(region_data[region]['lat']),
						parseFloat(region_data[region]['lng']));
	ihcc.map.setCenter(point, region_data[region]['zoom']);
};

ihcc.setupMarkers = function() {
	for (i=1; i<=5; i++) {
		var prefix = ihcc.markerSelectionPrefix[i];
		ihcc.markerSelection[i] = {};
		for (j=0; j<=1; j++) {
			var suffix = ihcc.markerSelectionSuffix[j];
			var markerIcon = new GIcon();
			markerIcon.image = prefix+suffix;
			markerIcon.iconSize = new GSize(32,32);
			markerIcon.iconAnchor = new GPoint(16,16);
			markerIcon.infoWindowAnchor = new GPoint(32,0);
			ihcc.markerSelection[i][j] = { icon:markerIcon };
		}
	}
};

ihcc.startRegistration = function() {
	var stackContainer = dijit.byId('ihcc_container_register_wizard');
	dojo.style(dojo.byId('subMenuRegister'), 'fontWeight', 'normal');
	dojo.style(dojo.byId('subMenuRegister1'), 'fontWeight', 'bold');
	stackContainer.forward();
};

ihcc.regionChanged = function() {
	ihcc.setCenterToRegion(dijit.byId("regionDropdown").getValue());
};