/*
 * Dr.Blumer - Javascript Library
 *
 * Copyright (c) 2011 Adwired AG
 */

/*
 * variables
 */

var clientWidth;
var clientHeight;
var resizeTimer	= null;
var dialogCount	= 0;
var footerLeft = 1;
var footerRight = 2;

/*
 * initialize
 */
$(document).ready(function() {
	// get the client size
	//
	clientWidth		= self.innerWidth || jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth;
	clientHeight	= self.innerHeight || jQuery.boxModel && document.documentElement.clientHeight || document.body.clientHeight;
	
	// set datepicker localization
	//
	$.datepicker.setDefaults($.datepicker.regional['']);
	$.datepicker.setDefaults($.datepicker.regional['de-CH']);

	// catch ajax errors
	//
	$(document).ajaxError(function(e, xhr, settings, exception) {
		alert('Error in: ' + settings.url + "\nError: " + xhr.status + ' ' + xhr.statusText);
	});

	// check the cookies
	//
	if (getCookie('dr-blumer-language') == null) {
		setCookie('dr-blumer-language', 'ger', 365);
	} else {
		toggleSiteLanguage(getCookie('dr-blumer-language'), true);
	}
	
	// start teaser "show off"
	//
	if ($('#teaser').children().length > 0) {
		// relocate the teaser
		//
		$teaser = $('#teaser');
		$('#teaser').remove();
		$('DIV.content').prepend($teaser);
		
		// show the teasers
		//
		$teaser.show();
		
		// start the show off
		//
		$('#teaser').jshowoff({
			speed:		4500,
			links:		false,
			controls:	false
		});
	}
	
	/*
	 * newsboards
	 */
	$('#disclaimer #btn-accept').click(function() {
		// hide the disclaimer and show the newsboard
		//
		$('#disclaimer').hide();
		$('#newsboard').show();
	});
	 
	$('#form-access-newsboard #btn-newsboard-send-code').click(function(e) {
		// stop event propagation
		//
		e.stopImmediatePropagation();
		
		// build the url
		//
		var newsboardURL = 'http://www.dr-blumer.ch/news/' + $('#field-access-newsboard-url').val() + '/' + $('#field-access-newsboard-code').val() + '/';
		
		// redirect the client
		//
		window.location = newsboardURL;

		// return
		//
		return false;
	});
	
	$('#form-request-action #btn-newsboard-request-access').click(function(e) {
		// stop event propagation
		//
		e.stopImmediatePropagation();
		
		// define the form options
		//
		var optionsRequestAccess = {
			dataType:	'json',
			success:	function(result) {
							alert('Herzlichen Dank für Interesse! Wir werden in Kürze mit Ihnen Kontakt aufnehmen.');
						},
			clearForm:	false
		};

		// submit the form
		//
		$('#form-request-action').ajaxSubmit(optionsRequestAccess);

		// return
		//
		return false;
	});
	
	/*
	 * intialize qtips
	 */
	$('A.qtip').qtip({
		style:	{
					width:		500,
					padding:	5,
					border:		{
									width:	1,
									radius:	5,
									color:	'#0B3365'
								},
					tip:		'topLeft',
				}
	});
});

/*
 * content handling
 */
function toggleSiteLanguage(newLanguage, noCookie) {
	// set the cookie
	//
	if (noCookie == null) {
		setCookie('dr-blumer-language', newLanguage, 365);
	}

	// toggle the content
	//
	if (newLanguage == 'ger') {
		$('#header-ger').removeClass('hidden');
		$('#content-ger').removeClass('hidden');
		$('#footer-ger').removeClass('hidden');
		$('#header-eng').addClass('hidden');
		$('#content-eng').addClass('hidden');
		$('#footer-eng').addClass('hidden');
	} else {
		$('#header-ger').addClass('hidden');
		$('#content-ger').addClass('hidden');
		$('#footer-ger').addClass('hidden');
		$('#header-eng').removeClass('hidden');
		$('#content-eng').removeClass('hidden');
		$('#footer-eng').removeClass('hidden');
	}
}

function checkDisclaimer() {
	// got the session cookie?
	//
	if (getCookie('dr-blumer-disclaimer') != null) {
		return;
	} else {
		// get the language
		//
		var siteLanguage = getCookie('dr-blumer-language');
		
		// build the buttons
		//
		var dialogButtons;
		if (siteLanguage == 'ger') {
			dialogButtons = {
				'Akzeptieren': function() {
					$(this).dialog('close');
					setCookie('dr-blumer-disclaimer', randomString(), 10);
				},
				'Ablehnen': function() {
					document.location = '/';
				}
			};
		} else {
			dialogButtons = {
				'Accept': function() {
					$(this).dialog('close');
					setCookie('dr-blumer-disclaimer', randomString(), 10);
				},
				'Decline': function() {
					document.location = '/';
				}
			};
		}
		
		// show the disclaimer
		//
		$('#disclaimer-' + siteLanguage).dialog({
			resizable:		false,
			width: 			600,
			height:			500,
			modal:			true,
			closeOnEscape:	false,
			dialogClass:	'dlg-disclaimer',
			buttons:		dialogButtons
		});
	}
}

function injectDialog(dialog, params) {
	// load the dialog definition and content
	//
	$.ajax({
		url:		'/xml/inject-dialog/',
		type:		'POST',
		data:		'dialog=' + dialog + '&' + params,
		dataType:	'xml',
		success:	function(data) {
						// create the dialog
						//
						var dialog = $('<div></div>')
							.html($(data).find('content').text())
							.dialog({
								position:	'center',
								modal:		$(data).find('modal').text() ? true : false,
								resizable:	$(data).find('resize').text() ? false : true,
								width:		$(data).find('width').text(),
								minWidth:	$(data).find('minWidth').text() || $(data).find('width').text(),
								height:		$(data).find('height').text(),
								minHeight:	$(data).find('minHeight').text() || $(data).find('height').text(),
								maxHeight:	clientHeight - 170,
								title: 		$(data).find('title').text(),
								close:		function(event, ui) {
												// call the module close method
												//
												if ($(data).find('closeCallback').text() != '') {
													var closeCallback = $(data).find('closeCallback').text();
													$.globalEval(closeCallback);
												}
									
												// close the dialog and remove it
												//
												$(this).dialog('destroy');
												$(this).remove();
											},
							});

						// open the dialog
						//
						dialog.dialog();
						
						// excecute code if available
						//
						if ($(data).find('code').text() != '') {
							$.globalEval($(data).find('code').text());
						}
					}
	});
}

function showConfirmation(title, msg) {
	// show the confirmation dialog
	//
	var dialog = $('<div></div>')
		.html('<p>' + msg + '</p>')
		.dialog({
			position:	'center',
			modal:		true,
			resizable:	false,
			title: 		title,
			buttons:	{
							Ok: function() {
								$(this).dialog('close');
							}
						},
			close:		function() {
							// close the dialog and remove it
							//
							$(this).dialog('destroy');
							$(this).remove();
						}
		});
	
	// open the dialog
	//
	dialog.dialog();
}

function getFactsheets(products, language) {
	// load the factsheets
	//
	$.ajax({
		url:		'/html/factsheets/',
		type:		'POST',
		data:		'language=' + language + '&products=' + products,
		dataType:	'html',
		success:	function(data) {
						// fill in the factsheets
						//
						$('#content-' + ((language == 1) ? 'ger' : 'eng') + ' DIV.content-factsheets').html(data);
					}
	});
}

/*
 * generic methods
 */

function classOf(o) {
	if (undefined === o) return "Undefined";
	if (null === o) return "Null";
	return {}.toString.call(o).slice(8, -1);
}

function scrollbarWidth() {
	// build the div
	//
	var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');

	// append our div
	//
	$('body').append(div);

	// do the calculation
	//
	var w1 = $('div', div).innerWidth();
	div.css('overflow-y', 'scroll');
	var w2 = $('div', div).innerWidth();

	// remove the div
	//
	$(div).remove();

	// return the scrollbar width
	//
	return(w1 - w2);
}

function textWidth(text_to_render) {
	// build the span
	//
	var span = $('<span id="temp-span" style="position:absolute;top:-200px;left:-200px;">' + text_to_render + '</span>');

	// append our span
	//
	$('body').append(span);

	// get the width
	//
	var text_width = $('#temp-span').width();

	// remove the span
	//
	$(span).remove();

	// return the width
	//
	return(text_width);
}

function replaceCSSClass(el, class1, class2) {
	el.removeClass(class1).addClass(class2);
};

function toggleButton(el, enable) {
	// enable the button?
	//
	if (enable) {
		if (classOf(el) == 'Array') {
			for (i=0; i < el.length; i++) {
				$(el[i]).removeAttr('disabled');
				$(el[i]).removeClass('disabled');
			}
		} else {
			$(el).removeAttr('disabled');
			$(el).removeClass('disabled');
		}
	} else {
		if (classOf(el) == 'Array') {
			for (i=0; i < el.length; i++) {
				$(el[i]).attr('disabled', 'disabled');
				$(el[i]).addClass('disabled');
			}
		} else {
			$(el).attr('disabled', 'disabled');
			$(el).addClass('disabled');
		}
	}
}

function toggleElement(el, enable) {
	// enable the element?
	//
	if (enable) {
		if (classOf(el) == 'Array') {
			for (i=0; i < el.length; i++) {
				$(el[i]).removeAttr('disabled');
				$(el[i]).removeClass('disabled');
			}
		} else {
			$(el).removeAttr('disabled');
			$(el).removeClass('disabled');
		}
	} else {
		if (classOf(el) == 'Array') {
			for (i=0; i < el.length; i++) {
				$(el[i]).attr('disabled', 'disabled');
				$(el[i]).addClass('disabled');
			}
		} else {
			$(el).attr('disabled', 'disabled');
			$(el).addClass('disabled');
		}
	}
}

function toggleFieldError(el, enable) {
	// enable the error class?
	//
	if (enable) {
		$(el).addClass('error');
	} else {
		$(el).removeClass('error');
	}
}

function sleep(milliseconds) {
	var start = new Date().getTime();
	for (var i = 0; i < 1e7; i++) {
		if ((new Date().getTime() - start) > milliseconds) {
			break;
		}
	}
}

function getTimestamp() {
	return Math.round(new Date().getTime() / 1000);
}

function highlight(el, keywords) {
	// highlight the keywords
	//
	for (i=0; i < keywords.length; i++) {
		// highlight the keywords
		//
		el.highlight(keywords[i]);
	}
}

function clearHighlighting(el) {
	// remove the highlighting
	//
	el.removeHighlight();
}

function isFunction(obj) {
	return $.isFunction(obj);
}

/*
 * strings
 */
function encode64(input) {
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	do {
		chr1 = input.charCodeAt(i++);
		chr2 = input.charCodeAt(i++);
		chr3 = input.charCodeAt(i++);

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) {
			enc3 = enc4 = 64;
		} else if (isNaN(chr3)) {
			enc4 = 64;
		}

		output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
		keyStr.charAt(enc3) + keyStr.charAt(enc4);
	} while (i < input.length);

	return output;
}

function decode64(input) {
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var output = "";
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	do {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));

		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		output = output + String.fromCharCode(chr1);

		if (enc3 != 64) {
			output = output + String.fromCharCode(chr2);
		}
		if (enc4 != 64) {
			output = output + String.fromCharCode(chr3);
		}
	} while (i < input.length);

	return output;
}

function textWidth(text_to_render) {
	// build the span
	//
	var span = $('<span id="temp-span" style="position:absolute;top:-200px;left:-200px;">' + text_to_render + '</span>');

	// append our span
	//
	$('body').append(span);

	// get the width
	//
	var text_width = $('#temp-span').width();

	// remove the span
	//
	$(span).remove();

	// return the width
	//
	return(text_width);
}

function randomString() {
	var chars = "0123456789ABCDEF";
	var string_length = 32;
	var randomstring = '';
	for (var i=0; i < string_length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum, rnum + 1);
	}
	return(randomstring);
}

/*
 * input fields related
 */
function adjustInputs(form_selector, override_field) {
	// get the width of the first text field
	//
	if (override_field == null) {
		var input_width = $(form_selector + ' SELECT:first:not(.fill):not(.noadj)').width();
		if (input_width == null) {
			input_width = $(form_selector + ' INPUT:text:first:not(.noadj)').width();
		}
	} else {
		var input_width = $(override_field).width();
	}
	
	// adjust the widths of all form fields
	//
	$(form_selector).find('INPUT:text:not(.time):not(.number):not(.date):not(.day):not(.filter):not(.noadj)').each(function() {
		$(this).width(input_width);
	});
	$(form_selector + ' SELECT:not(.fill):not(.filter):not(.noadj)').width(input_width + 5);
	$(form_selector + ' TEXTAREA:not(.fill):not(.noadj)').width(input_width - 3);
	$(form_selector + ' TEXTAREA.fill:not(.noadj)').each(function() {
		$(this).width($(this).width() - 3);
	});
}

function initDatePicker(el) {
	// initialize the date pickers
	//
	$('#' + el).datepicker( { dateFormat: 'dd.mm.yy' } );
	$('#img-' + el).click(function() {
		$('#' + el).datepicker('show');
	});
}

/*
 * loading panel
 */

function showLoader(message) {
	// set the message
	//
	var loader_message = message ? message : 'Daten werden geladen ...';

	// set the message
	//
	$('#loader SPAN').text(loader_message);

	// resize the loader
	//
	$('#loader').width(50 + textWidth(loader_message));

	// relocate the loading panel
	//
	$('#loader').css('top', (clientHeight / 2) - ($('#loader').height() / 2));
	$('#loader').css('left', (clientWidth / 2) - ($('#loader').width() / 2));

	// show the panel
	//
	$('#loader').fadeIn('fast');
}

function hideLoader() {
	$('#loader').fadeOut('fast');
}

/*
 * footer
 */
function setFooter(footer, message) {
	if (footer == footerLeft) {
		$('#footer-left SPAN').text('Status: ' + message);
	} else {
		$('#footer-right SPAN').text(message);
	}
}

function clearFooter(footer) {
	if (footer == footerLeft) {
		$('#footer-left SPAN').text('Status: - ');
	} else {
		$('#footer-right SPAN').text('');
	}
}

/*
 * tinymce
 */
function initEditor(field_id) {
	if (tinyMCE.get(field_id) == null) {
		tinyMCE.execCommand('mceAddControl', false, field_id);
	}
}

function removeEditor(field_id) {
	if (tinyMCE.get(field_id) != null) {
		tinyMCE.execCommand('mceRemoveControl', false, field_id);
	}
}

function fillEditor(field_id, content) {
	if ($('#' + field_id + '_parent').length) {
		tinyMCE.get(field_id).setContent(content);
	} else {
		$('#' + field_id).setValue(content);
	}
}

function removeEditors() {
	for (var ed in tinyMCE.editors) {
		removeEditor(tinyMCE.editors[ed].editorId);
	}
}

/*
 * cookies
 */
function getCookie(cookieName) {
	return $.cookie(cookieName);
}

function setCookie(cookieName, cookieValue, cookieExpires) {
	$.cookie(cookieName, cookieValue, { expires: cookieExpires, path: '/' });
}

