/*
 *  localization_handler.js
 *  this js-file is the controller for all localization requests/actions done by js clientside 
 *    
 */


/**
 * main handler method controls what to do on which page view and depending on available data
 * 
    These different types of localized pages types do exist: 
   
	overview pages with localized teaser(s) in marginal column: 
	* Dienstleistungsangebotsart 53
	* Bildungsangebotsart 57
	* Ehrenamtsart 66
			
	overview pages with googlemaps plugin
	* Einrichtungsangebotsart 55
	
	detail pages with localized teaser(s) in marginal column: 
	* Dienstleistungsangebot 54	
	* Bildungsangebot 58
	* Ehrenamt 67
	
	detail pages with no localized features
	* Einrichtungsangebot 56
		
 * 
 */

var localization_type = '';
var localization_str = '';
var _isLocalized = false;
var _offertypePageUid = 0;
var _offertypePageUrl = '';

function handleLocalization(locObject,doktype,offertypePageUid,pageZips,offertypePageUrl)
{	
	_offertypePageUid = offertypePageUid;
	_offertypePageUrl = offertypePageUrl;
	
	// doAjaxRequest(locObject,doktype,offertypePageUid);
	if(locObject)
	{
		switch(locObject['method']){
			case 'implicit':
				
				switch(locObject['type'])
				{
					case 'zip' : 
							// this case does not exist yet and will be ignored
							
						break;
					case 'uid' :
							// the localization was set on a institution page .. this is the uid of the page
							
						break;
				}			
				break;				
			case 'explicit':				
				
				switch(locObject['type'])
				{
					case 'zip' :									
							switch (doktype) {
								case 53 : 
								case 57 :									
									// select all available offers for this zip and the actual uid
									doAjaxRequest_offerOverview(locObject,doktype,offertypePageUid,offertypePageUrl);																	
									
							break;
								case 66 :
									// select all available offers for this zip and the actual uid
									doAjaxRequest_offerOverview(locObject,doktype,offertypePageUid,offertypePageUrl);
							break;
									
								case 55 : 
									// filter google maps markers
									localization_type = 'explicit';
									
									// needed by filterItemsByLocalization()
									localization_str = locObject['localizationString'];									
							break;
								case 54 : 
								case 58 :
								case 67 :
									
									$("#contact-header-unlocalized").show();
									
									// if the actual explizit localization doesnt fit to the actual page disable the explizit localization
									if(pageZips.length > 0)
									{
										// if this page contains localized content, test if the explicit localization matches this page .. if not disable the localization
										// can happen if the detailpage is called directly or with a deep link .. maybe from google or something like that
										var localizationMatched = false;										
										for(var i = 0; i < pageZips.length; i++)
										{
											// console.log(pageZips[i] + "," + locObject['localizationString']);
											if(matchingZip(pageZips[i],locObject['localizationString'])) {
												localizationMatched = true;
											}
										}								
										
										if(!localizationMatched)
										{
											// reset localization, but do not redirect to global offer page
											resetLocalization(doktype);																													
											
										} else {
											$("div.zipinfo").show();
											$("#localization-form-marginal-localized").addClass("localized");
											$("div#contact-header-localized").show();
											$("div#contact-title-localized").show();
											$("div#contact-header-unlocalized").hide();											
										}
										
									}
									
							break;
								case 56 :
									// no localization
							break;
								default: 
									// no localization
								break;
							}
						break;
					case 'uid' :
							// this case does not exist yet and will be ignored							
						break;
					default: 
						// no localization
					break;
				}			
				break;
				default: 
					// no localization
				break;
		}
		
		if(locObject['type']=='zip' && locObject['localizationString'] > 0)
		{
			showLocalizationForms_localized(locObject['localizationString']);
			_isLocalized = true;
		}		
	}	
}


function isLocalized()
{
	return _isLocalized;
}


function doAjaxRequest_offerOverview(locObject, doktype, uid, pageUrl)
{
	// eID TYPO3 request
	var requestURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
	
	// calls jo/ajax/class.ajax_offers.php function
	$.ajax(
	{
	  		type: "POST", 
	  		url: requestURL, 
	  		data: "eID=offers&locStr=" + locObject['localizationString'] + "&locType=" + locObject['type'] + "&doktype=" + doktype + "&uid=" + uid,
	  		// dataType:"json",
	  		success: function(msg){
				// alert(msg);		
				responseArr = JSON.parse(msg);
				
				items = responseArr[0]; // viell. brauchen wir noch mehr arrays im response array?
				
				if(items.length == 1)
				{
					// nur ein treffer = SPEZIALFALL ! sofortiger Redirect auf Angebotsdetailseite!
					tx_jo_redirectToPageUid(items[0].uid);
					
				} else if(items.length > 1) 
				{
					// anbieter als liste ausgeben
					render_VendorList(items);
					$("div#contact-header-localized").show();
					$("#localization-form-marginal-localized").addClass("localized");
					$("div.zipinfo").show();
										
				} else if(items.length == 0)
				{
					$("div.zipinfo").show();
					$("#localization-form-marginal-localized").addClass("localized");
					$("div#contact-header-localized").show();
					$("div#contact-title-localized").show();
					$("div#contact-header-unlocalized").hide();
					$("div#localization-form-marginal-localized div#error-1").show();
					$("div#error-4").show();
					$("div#hotlinebox").show();					
				}				
	   		}
	  });	 	
}


/**
 * this function will be called on every page which is considered to be localizable
 */
function getLocalizationStatus()
{
	if(document.cookie)
	{
		locObject = getLocalization();
		return locObject;
	}	
}

/**
 * Filters the jsondata array by the localized value.
 * IMPORTANT: handleLocalization() has to be called before this function ..
 * 
 * @param jsonData
 * @return localized items
 */
function filterItemsByLocalization(items_json)
{	
	// console.log("filterItemsByLocalization beginn : " + items_json);
	if(localization_str.length < 1) {
		return items_json;
	}
		
	var data = new Array();
	// iterate object attributes
	
	var index = 0;	
	$.each(items_json, function(i,dataObj){
				
		var remove = true;
					
		// iterate zips
		$.each(dataObj.zips, function(j,zip){
			if(matchingZip(zip,localization_str)) {
				remove = false;
			}
        });
			
		if(!remove) {
			data[index] = dataObj;
			index++;
		}
	});
	
	// console.log("filterItemsByLocalization ende : " + data);
	
	return data;
}


/**
 * Tests, if a zipcode matches the pattern.
 *  
 * @param zipPattern Zip pattern.
 * @param zipcode Zip code.
 * @return boolean
 */
function matchingZip(zipPattern, zipcode) {
	// replace all non digit chars
	zipcode = zipcode.replace(/\D/g, '');
	var regZip = zipPattern.replace('*', '.*');
	
	var pattern = eval('/^'+regZip+'/i');
	if(zipcode.match(pattern)) {
		return true;
	}
	
	return false;
}



/**
 * main controller method, which tries to set an explicit localization for a given zip string
 * @param zip
 * @return nothing
 */
function setLocalization_explicit(zip, form)
{	
	// first evaluate the zip - if erroreous put out error message
	if(tx_jo_checkGermanZipcode(zip))
	{	
		form_hideErrorMessage();
		
		// set cookie
		setLocalization(zip,'explicit');				
		
		// submit the actual zip onto the zip search page if the localization form in the header was used  
		if(form.attr('id') == 'localize-form')
		{		
			var searchPageURL = $(form).find('input.searchpagelink').val() + '&tx_jo_zip=' + zip;
			window.location.href = window.location.protocol + "//" + window.location.host  + "/" +  searchPageURL;
			// console.log(window.location.protocol + "//" + window.location.host + "/" + searchPageURL);
		} else {			
			
			if(_offertypePageUid > 0)
			{
				tx_jo_redirectToPageUid(_offertypePageUid);
			} else
			{
				// reload actual page, so that the cookie will be interpreted on reload
				window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search;
				
				
				// this doesnt work because a alert pops up if a form was submitted on the actual page			
				// window.location.reload();
			}
		}
	} else {		
				
		if(zip != 'Ihre PLZ')		
			form_showErrorMessage(form);
		
	}
}

/**
 * main controller method, which tries to set an explicit localization for a given zip string
 * @param zip
 * @return nothing
 */
function setLocalization_explicit_at(zip, form)
{	
	// first evaluate the zip - if erroreous put out error message
	if(tx_jo_checkGermanZipcode(zip))
	{	
		form_hideErrorMessage();
		
		// set cookie
		setLocalization(zip,'explicit');
		
		// submit the actual zip onto the zip search page if the localization form in the header was used  
		if(form.attr('id') == 'localize-form')
		{	
			var searchPageURL = $(form).find('input#searchpagelink'+zip).val();
			window.location.href = window.location.protocol + "//" + window.location.host  + "/" +  searchPageURL;
//			console.log(window.location.protocol + "//" + window.location.host + "/" + searchPageURL);
		} else {
			if(_offertypePageUid > 0)
			{
				tx_jo_redirectToPageUid(_offertypePageUid);
			} else
			{
				// reload actual page, so that the cookie will be interpreted on reload
				window.location.href = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search;
				
				// this doesnt work because a alert pops up if a form was submitted on the actual page			
				// window.location.reload();
			}
		}
	} else {
		
		if(zip != 'Bitte wählen Sie')
			form_showErrorMessage(form);
		
	}
}

/**
 * 
 * @param doktype
 * @param zip
 * @return array of explicitly localized offers or false if nothing found
 */
function getLocalizedOffers_explicit(doktype,zip)
{
	// ajax request against pages table by a given doktype and zip
	// returns an array of explicitly localized offers or false if nothing found
}

/**
 * 
 * @param doktype
 * @param institution_uid
 * @return array of explicitly localized offers or false if nothing found
 */
function getLocalizedOffers_implicit(doktype,institution_uid)
{
	// ajax request against pages table by a given doktype and an institution_uid
	// returns an array of explicitly localized offers or false if nothing found
}

/**
 * used by the google maps plugin
 * @param zip
 * @param facilitiesArr
 * @return array of facilities
 */
function getLocalizedFacilities_explicit(zip, facilitiesArr)
{
	// filters a given list of facilities by the zip 
	// returns a array of localized offers or false if nothing found
}

/**
 * used by the google maps plugin
 * @param institution_uid
 * @param facilitiesArr
 * @return
 */
function getLocalizedFacilities_implicit(institution_uid, facilitiesArr)
{
	// filters a given list of facilities by the institution_uid 
	// returns a array of localized offers or false if nothing found
}
