/**
* @author $Author: de-gha $
* @version $Revision: 5 $ $Date: 2008-07-23 11:13:36 +0200 (Mi, 23 Jul 2008) $
* @package pentax
* @internal tabsize 2 (no spaces)
* @internal $HeadURL: http://web-cms5/svn/pentaxeurope.com/js/init.js $
* @internal $Id: init.js 5 2008-07-23 09:13:36Z de-gha $
*/

var selected_division = '';
var db_division_names = {
	IS:		'photo',
	LC:		'medical',
	SSD:	'cctv',
	SO:		'sport optics',
	Surv:	'others'
};
var map;
var bubble; // mapInfo
var Location;
var Params = new Object();

$(document).ready(
	function() {

		//$('div.PE_sensitive').pngFix( );
		/* Parameter-String in ein Objekt umwandeln */
		var qsArray = window.location.search.substring(1).split('&');
		for ( var i = 0; i < qsArray.length; i++ )
		{
			var kv = qsArray[i].split('=');
			Params[kv[0]] = kv[1];
		}

		$('.PE_divisionBox dl').hover(
			function() {
				div = $(this).attr('id').substr(3);
				if ( selected_division != div)
				{
					$(this).children('.PE_divisionBoxContent').fadeIn();
// hja, neu:
					//$('#PE_divisionNaviContent_'+div).children('.PE_sensiNavi').fadeIn();
				}
			},
			function() {
				div = $(this).attr('id').substr(3);
				if ( selected_division != div)
				{
					$(this).children('.PE_divisionBoxContent').fadeOut();
// hja, neu:
					//$('#PE_divisionNaviContent_'+div).children('.PE_sensiNavi').fadeOut();
				}
			}
		);

		$('.PE_sensitive').hover(
			function() {
				$(this).children('.PE_sensiNavi').fadeIn();
			},
			function() {
				$(this).children('.PE_sensiNavi').fadeOut();
			}
		);

		$('.PE_sensiNaviEuropeUL li').hover(
			function() {
				div = $('a', this).attr('id').substr(3);
				$(this).css('background-position','0 -30px');
/*
				if ( selected_division != div)
					$('#PE_divisionBox'+div+' .PE_divisionBoxContent').fadeIn();
*/
			},
			function() {
				div = $('a', this).attr('id').substr(3);
				$(this).css('background-position','0 0');
/*
				if ( selected_division != div)
					$('#PE_divisionBox'+div+' .PE_divisionBoxContent').fadeOut();
*/
			}
		);

		$('.PE_sensiNaviSubsidiary li').hover(
			function() {
				$(this).css('background-position','0 -30px');
			},
			function() {
				$(this).css('background-position','0 0');
			}
		);

		// Click in der Division-Bar
		$('.PE_selectDivision').click(
			function() {
				// Bubble der Map ausblenden falls vorhanden
				if (typeof bubble == 'object') bubble.hide();

				$(this).blur();

				// Division in der Division-Bar aktivieren
				$('.PE_divisionBoxContent').hide();
				target = $(this).attr('id');


				switch (target) {
					case 'PE_IS':
						selected_division = 'IS';
						division = 'Imaging Systems';
						div = 'photo';
						break;
					case 'PE_SO':
						selected_division = 'SO';
						division = 'Sport Optics';
						div = 'sport optics';
						break;
					case 'PE_LC':
						selected_division = 'LC';
						division = 'Life Care';
						div = 'medical';
						break;
					case 'PE_SSD':
						selected_division = 'SSD';
						division = 'Security Systems';
						div = 'cctv';
						break;
					case 'PE_Surv':
						selected_division = 'Surv';
						division = 'Surveying';
						div = 'surveying';
						break;
					default:
						selected_division = 'Europe';
						division = 'none';
						div = 'none';
				};

				$('#PE_divisionBox'+selected_division+' .PE_divisionBoxContent').show();

				// Division-Label austauschen
				bg_image = 'src/BG_divisionLabel_'+selected_division+'.gif';
				l = $('#PE_divisionLabel');
				l.fadeOut('slow',
					function () {
						l.css('background-image','url('+bg_image+')');
						l.fadeIn();
					}
				);
				$('.PE_sensitive').show();
				lc = $('#PE_contentLeftWrap');
				lc.css('background-image','none');
				$('#PE_contentLeft',lc).html('');
				rc = $('#PE_contentRight');
				$.ajax({
  				url: "RC_Addresses/ajax_getAddressList.php",
  				data: 'div='+div,
  				cache: false,
  				success: function(html){
    				rc.html(html);
						initAccordion(rc);
						initClicks(rc);
						rc.fadeIn();
  				}
				});
			}
		);
		if (Params['division'] != '')
		{
			$('#PE_'+Params['division']).trigger('click');
		}
		// Content-Box mit JS-Warnung ausblenden
		hideContentBox();


	}
);

//****************
// Select Country
//****************
function initClicks(e){
	$('.PE_country h4', e).click(
		function(){
			if (typeof bubble == 'object') bubble.hide();
			$('h4.selected').removeClass('selected');
			$(this).addClass('selected');
			$('#PE_contentLeftWrap').hide();
			id = $(this).parent().attr('id');
			cb = $(this).siblings('.PE_countryInfo');
			$('.PE_countryInfo:visible').slideUp('slow');
			$.ajax({
				url: "RC_Addresses/ajax_getAddressDetails.php",
				data: "id="+id,
				cache: true,
				success: function(html) {
					cb.html(html);
					cb.slideDown('slow');
				}
			});
		}
	);
};

function initAccordion(e){
		$('.PE_countrySections', e).accordion({
		    autoheight: false,
		    header: 'h3',
		    alwaysOpen: true,
		    active: false
		});
		$('h3',e).hover(
			function() {
				$(this).addClass('hover');
			},
			function() {
				if ( $(this).attr('class') != 'selected')
					$(this).removeClass('hover');
			}
		);
}

// Just for Debugging
function outputObject(o) {
	var ret = '';
	for (var key in o)
	{
		ret = ret + key + ' : ' + o[key] + '\n';
	}
	return ret;
}

//**************
//* GOOGLE MAPS
//**************

// Show Map-Area
function showMap(loc) {
	$.ajax({
			url: "GoogleMaps/ajax_map.php",
			cache: false,
			success: function(html){
				e = $('#PE_contentLeftWrap');
				e.css('background-image','url(src/contentLeftBG.gif)');
				e.fadeIn('slow');
				$('.PE_sensitive').hide();
 				$('#PE_contentLeft', e).html(html);
 				initMap(Location);
			}
	});
}

// Marker-Class
function Marker(lat,lng)
{
	this.key	= '';
	this.name	= '';
	this.city	= '';
	this.gll	= new GLatLng(lat, lng);
	this.icon	= new GIcon();
	this.zoom	= 13;
}

// Initialize Map
function initMap(m) {
  if (GBrowserIsCompatible()) {
		$('a.PE_mapTypeBtn').click(
			function() {
				changeMapType($(this).attr('rel'));
			}
		);

    map = new GMap2(document.getElementById("PE_map"));
    map.addControl(new GLargeMapControl());

  	$.getScript('js/ebubble.js',
  		function()
  		{
	      // == Create an EBubble ==
	      bubble = new EBubble(map, "src/BG_bubble.png",new GSize(266,229), new GSize(234,124), new GPoint(12,12), new GPoint(40,229), true);
	      bubble.hide();
  		}
  	);
    showMarker(m);
  }
}

// Show the Map-Marker at Location
function showMarker(m)
{
	var gm  = new GMarker(m.gll, m.icon);


	GEvent.addListener(gm, 'click', function() {
		/*
		map.openInfoWindowHtml(
			m.gll,
			createInfoWindow()
		);
		*/
		bubble.openOnMarker(gm, createInfoWindow());
		//	toggleInfo(m);
	});


	map.setCenter(m.gll, m.zoom);
	//map.panBy(new GSize(-50,50));
	map.addOverlay(gm);
	$('#PE_mapInfo').hide();
}

// Create the HTML of the mapInfoWindow
function createInfoWindow()
{
	html	= '<table cellspacing="0" id="PE_mapInfoTable">';
	if (loc.name != '')
		html += '<tr id="PE_mapName"><td class="label">Company:</td><td class="value">'+ loc.name +'</td></tr>';
	if (loc.adr1 != '')
		html += '<tr id="PE_mapAdr1"><td class="label">Address:</td><td class="value">'+ loc.adr1 +'</td></tr>';
	if (loc.adr2 != '')
		html += '<tr id="PE_mapAdr2"><td class="label"></td><td class="value">'+ loc.adr2 +'</td></tr>';
	if (loc.adr3 != '')
		html += '<tr id="PE_mapAdr3"><td class="label"></td><td class="value">'+ loc.adr3 +'</td></tr>';
	if (loc.adr4 != '')
		html += '<tr id="PE_mapAdr4"><td class="label"></td><td class="value">'+ loc.adr4 +'</td></tr>';
	if (loc.cntry != '')
		html += '<tr id="PE_mapCountry"><td class="label"></td><td class="value">'+ loc.cntry +'</td></tr>';
	if (loc.web != '')
		html += '<tr id="PE_mapWeb"><td class="label">Website:</td><td class="value"><a href="http://'+ loc.web +'" target="_blank">'+ loc.web +'</a></td></tr>';
	if (loc.email != '')
		html += '<tr id="PE_mapMail"><td class="label">E-mail:</td><td class="value"><a href="javascript:showContactForm('+loc.id+');">email us</a></td></tr>';
	if (loc.phone != '')
		html += '<tr id="PE_mapPhone"><td class="label">Phone:</td><td class="value">'+ loc.phone +'</td></tr>';
	html += '</table>';
	html += '<div id="PE_mapInfoClose" onclick="bubble.hide();"></div>';
	return html;
}

// Change the Map type
function changeMapType(type)
{
	switch (type) {
		case 'Hybrid':
  	map.setMapType(G_HYBRID_MAP);
			break;
		case 'Satellite':
  	map.setMapType(G_SATELLITE_MAP);
			break;
		case 'Map':
  	map.setMapType(G_NORMAL_MAP);
			break;
	}
}

// Show/Hide the mapInfoWindow (eBubble)
function toggleInfo(m) {
	e = $('#PE_mapInfo');
	e.text(m.name);
	e.css('top','45px').css('left','200px');
	e.toggle();
}

//
function showMapRow()
{
	$('h4.selected').siblings('.PE_countryInfo').find('tr#PE_adrMap').show();
}

// Try to get the GeoLocation
function saveGeoLocation(id, lat, lng)
{
	$.ajax({
		type: 'POST',
		url: 'RC_Addresses/ajax_saveGeoLocation.php',
		data: 'id='+id+'&lat='+lat+'&lng='+lng
	});
}

/******************
* Kontaktformular
*******************/
function showContactForm(loc) {
	if (typeof bubble == 'object') bubble.hide();
	$.ajax({
//			url: "ContactForm/ajax_getContactForm.php",
			url: "ContactForm/ajax_getContactForm.php?id="+loc+"&div="+db_division_names[selected_division],
//			data: 'id='+loc+'&div='+db_division_names[selected_division],
			cache: false,
			success: function(html){
				e = $('#PE_contentLeftWrap');
				e.css('background-image','url(src/contentLeftBG.gif)');
				$('.PE_sensitive').hide();
 				$('#PE_contentLeft', e).html(html);
				e.fadeIn('slow');
				initContactForm();
			}
	});
}

function hideContentBox()
{
	$('#PE_contentLeftWrap').fadeOut('slow',
		function() {
			$('#PE_contentLeft').html('');
			$('.PE_sensitive').show();
		}
	);
}

function initContactForm()
{
	$.getScript('js/jquery.autocomplete.js');
	$.getScript('js/jquery.form.js',
		function() {
  		$.getJSON(
  			'RC_Addresses/ajax_getCountryList.php','',
  			function(data)
  			{
  				countryList = data;
					$('input#country').autocomplete(
						{ get : getMatches,
							multi: false,
							minchars: 2,
							timeout: 10000,
							delay: 500
						}
					);
  			}
  		);
			$.getScript('js/jquery.validate.js',
				function() {
		  	  var options = {
		  	  	onfocusout: false,
		  	  	onkeyup: false,
		  		  submitHandler: function(form) {
		   				$(form).ajaxSubmit({target: '#PE_contentLeft'});
		   			},
		   			rules:
		   			{
		   				firstname:	"required",
		   				lastname:		"required",
		   				country:		"required",
		   				email:			{ required: true, email: true },
		   				message:		"required"
		   			},
		   			messages:
		   			{
		   				firstname: 	"Please enter your firstname",
		   				lastname:		"Please enter your lastname",
		   				country:		"Please select your country",
		   				email:
		   				{
		   					required: "Please enter your email address",
		   					email:		"Your email address must be in the format of name@domain.com"
		   				},
		   				message:		"Please enter your message"
		   			},
		   			errorClass: 'missing',
		   			errorLabelContainer: "#PE_contactFormHint",
		   			errorContainer: "#PE_contactFormHint, #PE_contactFormHintBG",
		   			showErrors: function(errMap, errList) {
		   				if (errList.length == 0) return;
		   				var head = '<h4>Hint:</h4>';
		   				var hint = '';
		   				var foot = '<em>Required and missing fields are marked.</em>';
		   				for ( i in errList ) {
		   					$(errList[i].element).addClass('missing');
		   					hint += '<li>'+errList[i].message+'</li>';
		   				}
		   				showContactFormHint(head+'<ul>'+hint+'</ul>'+foot);
		   			}
		   		}
		  	  $('#PE_contactForm').validate(options);
		  	}
			);
  	}
  );
 	$('#PE_contactFormClose').click(
 		function() {
 			hideContentBox();
 		}
 	);
}

function checkContactForm(formData, jqForm, options) {
    // jqForm is a jQuery object which wraps the form DOM element
    //
    // To validate, we can access the DOM elements directly and return true
    // only if the values of both the username and password fields evaluate
    // to true

 		var fail = false;
 		var missing = '';
 		var hint = '';
    var form = jqForm[0];
    var required = $('.required',form);

    required.removeClass('missing');
    for ( var i = 0; i < required.size(); i++)
    {
    //alert(outputObject(required[i]));
    	e = required[i];
    	value = $(e).val();
    	//alert(outputObject(e));
    	if (value == '') {
    		$(e).addClass('missing');
    		missing = $(e).attr('title');
				hint += missing + "<br />";
    		fail = true;
    	}
    }
    if ( fail ) {
			head = '<h4>Hint:</h4>';
			hint += '<em>Required and missing fields are marked.</em>';
    	showContactFormHint(head+hint);
			return false;
		}
		else
		{
			return true;
		}
}

function showContactFormHint(msg) {
	e = $('#PE_contactFormHintBG, #PE_contactFormHint');
	$('#PE_contactFormHint').append(msg);
	if ( $.browser.msie )
	{
		// Selects im IE ausblenden
		$('#PE_contactForm select').css('visibility', 'hidden');
	}
	e.fadeIn();
	setTimeout('hideContactFormHint()', 3000);
}

function hideContactFormHint() {
	$('#PE_contactFormHintBG, #PE_contactFormHint').fadeOut();
	$('#PE_contactFormHint').html('');
	if ( $.browser.msie )
	{
		// Selects im IE wieder einblenden
		$('#PE_contactForm select').css('visibility', 'visible');
	}
}
function getMatches(typed)
{
	var a = Array();
 	for(var i=0;i<countryList.length;i++)
 	{
		if (countryList[i].country_name_en.match(new RegExp("^"+typed, "i")))
		{
   		a.push({id:countryList[i].country_id, value:countryList[i].country_name_en, info:"country id #"+i, extra:'extra fields remains!'});
   	}
 	}
   return a;
}

function getContents(url)
{
	if (typeof bubble == 'object') bubble.hide();
	$.ajax(
		{
			url: url,
			cache: false,
			success: function(html){
				e = $('#PE_contentLeftWrap');
				e.css('background-image','url(src/contentLeftBG.gif)');
				$('.PE_sensitive').hide();
 				$('#PE_contentLeft', e).html(html);
				e.fadeIn('slow');
			 	$('.PE_contentClose').click(
			 		function() {
			 			hideContentBox();
			 		}
			 	);
			}
		}
	);
	return false;
}

