/**
 * Additional JavaScript which is used by catalog and shop.
 * Compressed version will be merged with viega.js
 * 
 * @author       ecomplexx, www.ecomplexx.com
 * @version      $Revision: 171 $ 
 * @date         $Date: 2009-04-20 16:16:35 +0200 (Mo, 20 Apr 2009) $ 
 */


/**
 * Convert XML string to DOM document
 *
 * @param        {String}  xmlString
 * @return       {DOM}                  DOM document (NULL on errors)
 */
function toXml(xmlString) {
	if (window.ActiveXObject)
	{
		doc = new ActiveXObject('Microsoft.XMLDOM');
		doc.async = false;
		doc.loadXML(xmlString);
	} else {
		doc = (new DOMParser()).parseFromString(xmlString, 'text/xml');
	}	
	return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
}


/**
 * Removes all namespaces from Ajax results
 *
 * @private
 * @param        {String} data  raw data from Ajax request
 * @return       {String}       data without namespaces
 */
function clearNamespace(rawData) {
	var rawXml = rawData.replace(/[\n\r]/g, '');
	rawXml = rawXml.replace(/(<|<\/)[\w\d]+?:/g, '$1');
	
	// Remove unneeded information from LiveServer XML
	rawXml = rawXml.replace(/<!DOCTYPE.+?\]>/g, '');
	rawXml = rawXml.replace(/<webshop.+?>/g, '<webshop>');
	return rawXml;
}


/**
 * Default jQuery Ajax parameters
 */
$.ajaxSetup({
	async:      false,
	dataFilter: function(rawData) {
		var xmlString = clearNamespace(rawData);
		return toXml(xmlString);
	},
	dataType:   'text',
	type:       'GET'
});


/**
 * Shows error message
 *
 * @private
 * @param        {String} message  error message
 * @return       {Bool}            false
 */
function showErrorMessage(message) {
	$('#error').html(message).vCenter().show();
	return false;
}


/**
 * Custom jQuery selector for exact text matches
 *
 * @addon        jQuery
 * @return       {Bool}
 */
$.expr[":"].exact = function(el, i, m) {
    var search = m[3];        
    if (!search) { return false; }
    return $(el).text() === search;
};


/**
 * Format MySQL date
 *
 * @private
 * @param        {String} mysqlDate  MySQL date (YYYY-MM-DD HH:MM:SS.MS)
 * @param        {String} format     target format with placeholders:
 *                                   YYYY = year, MM = month, DD = day, hh = hour, mm = minutes, ss = seconds
 * @return       {String}            Formated string
 */
function formatMysqlDate(mysqlDate, format) {
	var date = mysqlDate.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}).(\d{1,2})$/);
	return format.replace(/YYYY/g, date[1]).replace(/MM/g, date[2]).replace(/DD/g, date[3]).replace(/hh/g, date[4]).replace(/mm/g, date[5]).replace(/ss/g, date[6]);
}


// Functions extending the jQuery object
jQuery.fn.extend({
	/**
	 * Table zebra striping, allows chaining
	 * Example: $('#mytable').stripe()
	 * 
	 * @addon        jQuery
	 * @return       {jQuery}
	 */
	stripe: function() {
		this.removeClass();
		this.filter(':odd').addClass('even');
		this.filter(':even').addClass('odd');
		return this;
	},
	
	/**
	 * Vertical positioning in the viewport (www.learningjquery.com)
	 * 
	 * @addon        jQuery
	 */
	vCenter: function() {
		var pos = {
			sTop : function() { return window.pageYOffset || document.documentElement && document.documentElement.scrollTop ||	document.body.scrollTop; },
			wHeight : function() { return window.innerHeight || document.documentElement && document.documentElement.clientHeight || document.body.clientHeight; }
	    };
	    return this.each(function(index) {
			if (index === 0)
			{
				var $this = $(this);
				var elHeight = $this.height();
			    var elTop = pos.sTop() + (pos.wHeight() / 2) - (elHeight / 2);
				$this.css({
					position: 'absolute',
					marginTop: '0',
					top: elTop
				});
			}
		});
	},
	
	/**
	 * Submits a form via Ajax and handles response
	 * Accepts three functions as option parameters: beforeSubmit, success and error 
	 * Example: 
	 * $('#myform').ajaxFormHandler({ 
	 *     beforeSubmit:  myBeforeFunction,
	 *     success:       mySuccessFunction,
	 *     error:         myErrorFunction;
	 * });
	 * 
	 * @addon          jQuery
	 * @param {Object} options
	 */
	ajaxFormHandler: function(options) {
		var form = $(this);
		form.submit(function(){
			var formQueryString = form.serialize();

			// If beforeSubmit function exists, check for validations errors
			if (options.beforeSubmit && typeof options.beforeSubmit === 'function')
			{
				formQueryString = options.beforeSubmit(formQueryString);
				if (formQueryString === false) { return false; }
			}

			$.ajax({
				url: /*(options.action && options.action !== '') ? options.action : */ form.attr('action'),
				type: form.attr('method') || 'GET',
				data: formQueryString,
				success: function(response) { if (options.success && typeof options.success === 'function') { options.success(response); } },
				error: function(request, errorType, errorThrown) { if (options.error && typeof options.error === 'function') { options.error(errorType, errorThrown); } }
			});

			// IMPORTANT: Always return false to prevent standard browser submit and page navigation 
			return false;
		});
	}
});


// Check for browsers
var isSafari3 = (window.devicePixelRatio) ? true : false;
var isIE = false /*@cc_on || @_jscript_version <= 5.7 @*/;

// Avoid JavaScript errors from browsers without console.log function
if (typeof window.console === 'undefined') { console={ log:function(){} }; }