/*

Theme Name: bo_t1
Theme URI:
Description: Javascript for BonOferta Template #1
Version: 1.0
Author: Henry Farkas
Author URI: http://www.emsone.com/
Tags:

*/

//console.log("bo_t1.js included");

// ------------------------------------------------------------------
// constants

var _ue_ = String.fromCharCode(0xFC);
var _Ue_ = String.fromCharCode(0xDC);

var _ae_ = String.fromCharCode(0xE4);
var _Ae_ = String.fromCharCode(0xC4);

var _oe_ = String.fromCharCode(0xF6);
var _Oe_ = String.fromCharCode(0xD6);

var _sz_ = String.fromCharCode(0xDF);

// ------------------------------------------------------------------
// global functions

// returns index of obj in array
function getIndex(array,obj) {
   for (var i=0; i<array.length; i++) {
      if (array[i] == obj) return i;
   }
}

function trim(str) {
  // Erst führende, dann Abschließende Whitespaces entfernen
  // und das Ergebnis dieser Operationen zurückliefern
  return str.replace (/^\s+/, '').replace (/\s+$/, '');
}

function replaceUmlaute(str) {

	str = str.replace(new RegExp(/ü/g), _ue_);
	str = str.replace(new RegExp(/Ü/g), _Ue_);

	str = str.replace(new RegExp(/ä/g), _ae_);
	str = str.replace(new RegExp(/Ä/g), _Ae_);

	str = str.replace(new RegExp(/ö/g), _oe_);
	str = str.replace(new RegExp(/Ö/g), _Oe_);

	str = str.replace(new RegExp(/ß/g), _sz_);

	return str;
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll)
	return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}


// ------------------------------------------------------------------
// init function (called when html doc is fully loaded)
function init() {

	//console.log("init called");

	// HEADER NAVIGATION
	// replace txt based links with images
	var i = 0;
	jQuery('#header .nav .pagenav .page_item').each(function() {
		if (jQuery(this).hasClass('current_page_item')) {
			jQuery('.menu-element-name', this).replaceWith(
				'<div class="btn out"><img src="' + _tmplpath + '/img/n_' + _aSlugs[i] + '_out.png" /></div>' +
				'<div class="btn on"><img src="' + _tmplpath + '/img/n_' + _aSlugs[i] + '_on.png" /></div>');
		} else {
			jQuery('.menu-element-name', this).replaceWith(
				'<div class="btn out"><img src="' + _tmplpath + '/img/n_' + _aSlugs[i] + '_out.png" /></div>' +
				'<div class="btn over"><img src="' + _tmplpath + '/img/n_' + _aSlugs[i] + '_over.png" /></div>');
			// define listeners
			jQuery(this).bind('mouseenter', function() {
				jQuery('.btn', this).toggle();
			});
			jQuery(this).bind('mouseleave', function() {
				jQuery('.btn', this).toggle();
			});
			jQuery(this).bind('click', function() {
				jQuery('#header .nav .pagenav .current_page_item .btn').toggle();
				jQuery(this).unbind();
			});
		}
		i++;
	});
	// hide over images in inactive btns and out image in active btn
	jQuery('#header .nav .pagenav .page_item .over').hide();
	jQuery('#header .nav .pagenav .current_page_item .out').hide();
	// adjust css
	jQuery('#header .nav div.txt').toggleClass('txt').toggleClass('img');

	// FOOTER NAVIGATION
	// replace txt based links with images
	jQuery('#footer .imprint .pagenav .page_item .menu-element-name').replaceWith('<img src="' + _tmplpath + '/img/f_imprint.png" />');
	// adjust css
	jQuery('#footer .nav div.txt').toggleClass('txt').toggleClass('img');

	// --------------------------------------

	// set pdf download link functionality
	//jQuery('a.pdf_dl').bind("click", downloadPDF);

	// --------------------------------------
	// rel attribute value correction for shadowbox
	jQuery('#content-pane div.gallery a').each(function() {
		var sRel = jQuery(this).attr('rel');
		if (sRel) {
			sRel = sRel.replace(/\(/, '[');
			sRel = sRel.replace(/\)/, ']');
			jQuery(this).attr('rel', sRel);
		}
	});

	// --------------------------------------
	// initialize form
	initForm();

}


// ------------------------------------------------------------------
// pdf download

/*
function downloadPDF() {

	var sPathFileName = jQuery(this).attr('pathFileName');

	// create random number - to be appended to form name; this will solve issues in case of multiple use of downloadPHP script on same page.
	nRand = Math.floor(Math.random()*10001);

	// append fake form to a tag
	sForm = "<form name='fake_form_" + nRand + "' action='" + _tmplpath + "/php/downloadPDF.php' method='POST' style='display: none'><input name='pathFileName' id='pathFileName' value='" + sPathFileName + "' /></form>";
	jQuery(this).append(sForm);

	// submit form
	jQuery("form[name='fake_form_" + nRand + "']").submit();

	// remove form
	jQuery(this).children().empty();
}
*/


// ------------------------------------------------------------------
// border object and methods

function applyBorder(jqObject) {
	jqObject.css({
		borderColor: this.borderColor,
		borderStyle: this.borderStyle,
		borderTopWidth: this.borderTopWidth,
		borderRightWidth: this.borderRightWidth,
		borderBottomWidth: this.borderBottomWidth,
		borderLeftWidth: this.borderLeftWidth
	});
}

function Border(borderColor, borderStyle, borderTopWidth, borderRightWidth, borderBottomWidth, borderLeftWidth) {
	this.borderColor = borderColor;
	this.borderStyle = borderStyle;
	this.borderTopWidth = borderTopWidth;
	this.borderRightWidth = borderRightWidth;
	this.borderBottomWidth = borderBottomWidth;
	this.borderLeftWidth = borderLeftWidth;

	// assign method
	this.applyBorder = applyBorder;
}

function createBorder(jqObject) {
 	var border = new Border(
 		jqObject.css('border-color'),
 		jqObject.css('border-style'),
 		jqObject.css('border-top-width'),
 		jqObject.css('border-right-width'),
 		jqObject.css('border-bottom-width'),
 		jqObject.css('border-left-width')
 	);
 	return border;
}

// ------------------------------------------------------------------
// code for mailer form

// remember original style of input fields to allow reset of highlighted input elements
var oStyles = new Object();

// remember if errors on specific input fields have occured
var oErrors = new Object();

// init form
function initForm() {
	// add listeners for changes in form fields
	jQuery(':input').each(function() {
		if (
			jQuery(this).attr('id') == 'your_name' ||
			jQuery(this).attr('id') == 'email' ||
			jQuery(this).attr('id') == 'msg'
		) {
			//console.log('bind change action to: ' + jQuery(this).attr('id'));
			jQuery(this).change(function () {
				checkFormField(jQuery(this));
			});
		}
	});
	// hide original submit btn and add new one with js submitMail function bind to it
	var jqSubmitContainer = jQuery('form input.submit').parent();
	jQuery('form input.submit').remove();
	jqSubmitContainer.append('<input class="submit" type="button" name="Submit" value="Senden" />').bind('click', function() {
		submitMail(_pageurl + '/rcol/kontaktformular');
	});
}

// check field content
function checkFormField(jqInput) {
	// if Field is required, check if populated

	// get field id
	var sFieldId = jqInput.attr('id');

	//console.log("checkFormField() :: inputFieldID = " + sFieldId);

	// error message displayed to user
	var sErrorMsg = "";

	// set error state object property for current field
	if (!oErrors.hasOwnProperty(sFieldId)) oErrors[sFieldId] = false;

	// check if field has content
	if (!trim(jqInput.get(0).value)) {
		// error - required field empty

		// save original style to oStyles object if not already done
		if (!oStyles[sFieldId]) {
			oStyles[sFieldId] = new Object();
			oStyles[sFieldId].border = createBorder(jqInput.parent());
		}
		// change border of current input field
		// and set error flag as well as put error message
		// if not already done
		if (!oErrors[sFieldId]) {
			jqInput.parent().css({'border' : '2px solid red'});
			oErrors[sFieldId] = true;
			sErrorMsg = "Bitte füllen Sie das Feld aus.";
			jqInput.parent().after("<p style='color: red; font-weight: bold; margin: -8px 0 12px 0;'>" + replaceUmlaute(sErrorMsg) + "</p>");
		}
	} else {
		// check if oStyles object contains some information for current input field
		if (oStyles[sFieldId]) {
			// reset border
		 	oStyles[sFieldId].border.applyBorder(jqInput.parent());
		 	// delete border information from oStyles object
		 	delete oStyles[sFieldId];

		 	// delete error flag
		 	delete oErrors[sFieldId];

		 	// delete error message
		 	jqInput.parent().next().remove();
		}
	}


	// if input field is meant for email adresses, check adress format

	// set id of email input field
	var sEmailFieldId = 'email';

	if (jqInput.attr('name').toLowerCase() == sEmailFieldId && !oErrors[sEmailFieldId]) {
		// check mail adress
		var usr = "([a-zA-Z0-9][a-zA-Z0-9_.-]*|\"([^\\\\\x80-\xff\015\012\"]|\\\\[^\x80-\xff])+\")";
		var domain = "([a-zA-Z0-9][a-zA-Z0-9._-]*\\.)*[a-zA-Z0-9][a-zA-Z0-9._-]*\\.[a-zA-Z]{2,5}";
		var regex = "^"+usr+"\@"+domain+"$";
		var rxMail = new RegExp(regex);

		var jqEmailField = jqInput;
		var check = (rxMail.test(jqEmailField.val()));
		if (check!=true) {
			// error - email is not in acceptable format

			// save original style to oStyles object if not already done
			if (!oStyles[sEmailFieldId]) {
				oStyles[sEmailFieldId] = new Object();
				oStyles[sEmailFieldId].border = createBorder(jqEmailField.parent());
			}
			// change border of current input field
			// and set error flag as well as put error message
			// if not already done
			if (!oErrors[sEmailFieldId]) {
				jQuery(jqEmailField.parent()).css({'border' : '2px solid red'});
				oErrors[sEmailFieldId] = true;
				sErrorMsg = "Die von Ihnen angegebene Email-Adresse ist nicht korrekt.";
				jqInput.parent().after("<p style='color: red; font-weight: bold; margin: -8px 0 12px 0;'>" + replaceUmlaute(sErrorMsg) + "</p>");
			}
		} else {
			// check if oStyles object contains some information for current input field
			if (oStyles[sEmailFieldId]) {
				// reset border
		 		oStyles[sEmailFieldId].border.applyBorder(jqEmailField.parent());
		 		// delete border information from oStyles object
		 		delete oStyles[sEmailFieldId];

		 		// delete error flag
		 		delete oErrors[sEmailFieldId];

		 		// delete error message
		 		jqInput.parent().next().remove();
			}
		}
	}

	// change submit button label, if errors occured
	var count = 0;
	for (k in oErrors) if (oErrors.hasOwnProperty(k)) {
		if (oErrors[k]) count++;
	}

	if (count > 0) {
		jQuery('input.submit').attr('value', replaceUmlaute('Übernehmen'));
	} else {
	   jQuery('input.submit').attr('value', 'Senden');
	}
}

function submitMail(sURI) {

	var aFields = jQuery(':input').get();

	// check if required fields are populated
	for (var i=0; i<aFields.length; i++) {
		if (
			jQuery(aFields[i]).attr('id') == 'your_name' ||
			jQuery(aFields[i]).attr('id') == 'email' ||
			jQuery(aFields[i]).attr('id') == 'msg'
		) checkFormField(jQuery(aFields[i]));
	}

	var count = 0;
	for (k in oErrors) if (oErrors.hasOwnProperty(k)) {
		if (oErrors[k]) count++;
	}

	if (count > 0) {
		// no further processing because fields are missing or not populated correctly
	} else {

		addOverlay();

		var oData = new Object();

		// write form fields data into oData object
		for (var i=0; i<aFields.length; i++) {
			oData[jQuery(aFields[i]).attr('name')] = aFields[i].value;
		}
		// add one more key/value pair to object to tell pxsmail script, that we don't want to get back a full page, instead we only want info if successfully sent
		oData['simpleReturnValue'] = '1';

		jQuery.post(
			sURI,
			oData,
			function(data){

				if ( trim( data ).length > 0 ) displayMessageBox("Ihr Nachricht wurde erforlgreich versandt.", 200)
				else displayMessageBox("Der Versand war leider nicht erfolgreich, bitte versuchen Sie es erneut. Sollte dieser Fehler erneut auftreten kontaktieren Sie bitte den Administrator der Seite. Wir bitten die Unanehmlichkeiten zu entschuldigen.", 300);

			},
			"text"
		);
	}
}


// ------------------------------------------------------------------
// message layer

function displayMessage(sMsg, nWidth) {

	//console.log('displayMessage called');

	addOverlay();
	displayMessageBox(sMsg, nWidth);

}

// display grid overlay on top of page (disables all page controls)
function addOverlay() {

	var pageHeight = getPageSize()[1];

	var sMsgLayer =
		'<!-- message layer -->' +
		'<div id="messageLayer" ' +
		'style="position:absolute; top: 0px; left: 0px; width:100%; height:' + pageHeight + 'px; z-index: 100; background-image: url(' + _tmplpath + '/img/fullOverlay.gif)">' +
		'</div>';

	jQuery('body').append(sMsgLayer);
}

// works only if overlay had been applied already
function displayMessageBox(sMsg, nWidth) {
	var pageWidth = getPageSize()[0];
	var winHeight = getPageSize()[3];
	var scrollPos = getPageScroll()[1];

	jQuery('#messageLayer').append(
		'<div style="' +
		'border: 1px solid black; ' +
		'background: #f0cc85; ' +
		'width: ' + nWidth + 'px; ' +
		'height: auto; ' +
		'padding: 10px; ' +
		'cursor: pointer; ' +
		'text-align: center; ' +
		'position: relative; ' +
		'left: ' + (pageWidth/2 - nWidth/2) + 'px; ' +
		'top: ' + (winHeight/2 - 50 + scrollPos) + 'px;">' +
		'<p style="font-weight: bold; margin-bottom: 20px; line-height: 1.5;">' + replaceUmlaute(sMsg) + '</p>' +
		'<p style="font-size: 0.8em;">[x] Schließen</p>' +
		'</div>'
	).bind('click', function() {
		jQuery('#messageLayer').remove();
	});
}





