/*
 * File........: navcontrol.js
 * Created.....: 2008/09/11
 * Copyright...: (c) 2008 All Rights Reserved.
 */

// Aenderung der Ansicht
function changeView(act, i)
{
	var same = document.p.act.value == act;
	document.p.act.value = act;
	if(i < 0) {
		i = -i;
		same = false;
	}
	document.p.v.value = i;
	if(same && $('form').is('form.vtpAjax')) {
		document.p.action = "controller.content_fragment.do";
		$('form.vtpAjax').trigger('submit');
	}
	else {
		document.p.submit();
//		document.body.style.cursor='wait';
	}
}

//Aenderung der Fahrzeugauswahl
function changeSelection(i)
{
	document.p.v.value = 0;
	if(i && document.p.show) {
		document.p.show.value = 0;
	}
	document.p.act.value = "search";
	document.p.tab.value = (i) ? 'all' : 'chg';
	document.p.submit();
}

// Detailansicht eines Fahrzeugs
function carDetails()
{ 
	document.p.act.value = "offer";
	document.p.submit();
}

function getViewStat() {
	var count=8;
	var stat = '';
	for(var i=1;i<=count;i++) {
		var ele=document.getElementById("a" + i);
		if (ele==null)
			return stat;
		var equTabStyle = ele.style;
		stat += (equTabStyle.display == "none") ? "1" : "0";
	} 
	return stat;
}
audi_ngw.config.sHostHTTP = "http://"+window.location.host;
audi_ngw.config.sHostHTTPS = "https://"+window.location.host;
audi_ngw.config.preload = new Array();

/**
 * AUDI JavaScript library: handles vtp ajax posting 
 * 
 * @projectDescription	vtp ajax forms
 */

/* create namespace */
audi_ngw.namespace(audi_ngw,'form.vtpAjax');
 

/* CREATE JQUERY PLUGINS */
/**
 * @see audi_ngw.dom.rounded_corners.create 
 */
$.fn.audi_vtpAjax = function() {
	audi_ngw.dom.vtpAjax._doSubmit(this);
	return this;
};
 
/**
 * Adds necessary events
 * @return {Void}
 */
audi_ngw.form.vtpAjax._addEvents = function() {
	// cache scope
	var scope = audi_ngw.form.vtpAjax;
	var _sSelector = 'form.';
	_sSelector += scope._oOptions._sClassNameMarker;

	// add events on forms
	jQuery(_sSelector)
		.unbind('submit')
		.bind('submit.vtpAjax',audi_ngw.form.vtpAjax.submit)
		// set event on hide resetting elements in case a non-modal layer get closed during runnding request
		.parents('.audi_generated_corners_background')
		.find('.close')
		.unbind('click.vtpAjax')
		.bind('click.vtpAjax',audi_ngw.form.vtpAjax.hide);
};

/**
 * OnSubmit event
 * @param {Event} event
 * @return {Void}
 */
audi_ngw.form.vtpAjax.submit = function (event) {
	// prevent default 
	event.preventDefault();
	// cache scope
	var scope = audi_ngw.form.vtpAjax;
	// construct selector for running request markers
	var _sSelector = 'form.';
	_sSelector += scope._oOptions._sClassNameMarker;
	_sSelector += ".";
	_sSelector += scope._oOptions._sClassNameActiveMarker;
	
	// just one request
	if(jQuery(_sSelector).size()) {
		return;
	}
	
	// get element from event 
	var _$element = jQuery(event.target) || jQuery(event);
	// do submit 
	audi_ngw.form.vtpAjax._doSumbit (_$element,event);
	// cancel default event 
	return false;
};

/**
 * Ajax sumbit
 * @see audi_ngw.form.validation.validatorForRequiredFields
 * @param {Element} jQuery element
 * @return {Void}
 */
audi_ngw.form.vtpAjax._doSumbit = function ($element) {
	// cache scope
	var scope = audi_ngw.form.vtpAjax;
	
	// prepare environment
	$element
		.parent()
//		.height($element.parent().height())
		.end()
		.addClass(scope._oOptions._sClassNameActiveMarker)
		.audi_setLoading();
	// get query param
	var _oFields = $element
		.find(":input")
		.serializeArray();
	// get url
	var _sUrl = $element.attr('action');
	// post 
	$.post(_sUrl,_oFields,audi_ngw.form.vtpAjax.onSuccess);
};

/**
 * inSuccess callback, injects HTML
 * @param {String} responseText
 * @return {Void}
 */
audi_ngw.form.vtpAjax.onSuccess = function(data) {
	
	$(data).each(function() {
		if($(this).attr('id')=='sessionTimeout') {
			url=$(this).text();
			window.location=url;
		}
	});
	
	// cache scope
	var scope = audi_ngw.form.vtpAjax;

	// construct selector for request owing form
	var _sSelector = 'form.';
	_sSelector += scope._oOptions._sClassNameMarker;
	_sSelector += ".";
	_sSelector += scope._oOptions._sClassNameActiveMarker;
	
	// is modal layer
	if (jQuery('#audi_modal_super_wrapper').css('display') !== 'none') {
		audi_ngw.layer.modal._$elLayer
		.find('#audi_modal_body')
		.replaceWith(	
		// Create a dummy div to hold the results
		jQuery("<div/>")	
			// inject the contents of the document in, removing the scripts
			// to avoid any 'Permission Denied' errors in IE 
			.append(data)	// .replace(/<script(.|\s)*?\/script>/g, '')	
			// Locate the specified elements
			.find(" #" + "audi_modal_body > *")
		);
		// evaluate scripts
		var _aScript = data.match(/<script(.|\s)*?\/script>/g);
		if (_aScript !== null && _aScript.length) {
			var _node = jQuery("<div/>").append(_aScript.join(' ')).empty().remove();
			_node = null;
		}
	}
	
	// simple form 
	else {
		// inject html 
		jQuery("#audi_content_wrapper")	// _sSelector remove height 
		//		.parent()
		//		.height('')
		//		.end()
		.html(
			jQuery("<div/>")
				// inject the contents of the document in, removing the scripts
				// to avoid any 'Permission Denied' errors in IE 
				.append(data.replace(/<script(.|\s)*?\/script>/g, ''))
				// Locate the specified elements
				.find(" #" + "audi_content_wrapper > *")
			);
	}
	// trigger event
	audi_ngw.event.trigger('ajaxSnippetReady',[{'sId': '#audi_container_page'}]);
	audi_ngw.event.trigger('ajaxPageLoadContentReady');
//	audi_ngw.form.vtpAjax.initializeVTP();

	// IE Fix for invalid <title /> after closed modalLayer
	// copy von audi.navigation.js
	if(document.title.indexOf('Audi') < 0) {
		// document.title = 'Audi';
		window.setTimeout(function(){
			var $iframe = jQuery("#jQuery_history");
			if( 0 !== $iframe.size() )
				$iframe[0].document.title = audi_ngw.navigation.title;
			document.title = audi_ngw.navigation.title;
		}, 3000);
	}
}; 

/**
 * Resets form in case of hiding non-modal layer during running request.
 * @param {Event} event
 * @return {Void}
 */
audi_ngw.form.vtpAjax.hide = function(event) {
	// get element
	var $element = jQuery(event.target) || jQuery(event);
	// bridge
	audi_ngw.form.vtpAjax._doHide($element);
};

/**
 * Resets form in case of hiding non-modal layer during running request.
 * @param {HTMLElement} $element, jQuery extended Element (.close)
 * @return {Void}
 */
audi_ngw.form.vtpAjax._doHide = function($element) {
 	// cache scope
	var scope = audi_ngw.form.vtpAjax;
	$element
		.parents('.audi_generated_corners_background')
		// get request owner (form)
		.find('form.'+scope._oOptions._sClassNameActiveMarker)
		// remove marker class
		.removeClass(scope._oOptions._sClassNameActiveMarker)
		// remove loader 
		.audi_unsetLoading();
		// reset height 
//		.parent()
//		.height('');
};

/**
 * Custom Event: wil be fired as soon as we filled the ajax-content into the modal layer, just before "xhrReallocate"
 * @param {Object} event
 * @param {Object} xhr
 */
audi_ngw.form.vtpAjax.onAjaxPageLoadContentReady = function(event,xhr){

//	audi_ngw.log("EVENT - ajaxPageLoadContentReady: audi_ngw.form.vtpAjax.onAjaxPageLoadContentReady",arguments);
	// execute funtions on new content
 	audi_ngw.form.vtpAjax._addEvents();
	
	// trigger event 
	audi_ngw.event.trigger('ajaxPageLoadContentPrepared');
//	audi_ngw.event.trigger('ajaxSnippetReady',[{'sId': '#audi_content_wrapper'}]);

//	audi_ngw.navigation.updatePage(audi_ngw.form.vtpAjax); -> uebergibt falschen Selector 
	audi_ngw.vtp.search.initialize();
	audi_ngw.vtp.list.initialize();
	audi_ngw.vtp.detail.initialize();
};

/**
 * Custom Event: wil be fired as soon as we filled the ajax-content into the modal layer, just before "xhrReallocate"
 * @param {Object} event
 * @param {Object} xhr
 */
audi_ngw.form.vtpAjax.onAjaxModalContentReady = function(event,xhr){
	// check if this xhr-response contains valid content
	if (!audi_ngw.url.hasXHRContent(xhr,event.timeStamp)) {return false;}
	audi_ngw.log("EVENT - ajaxModalContentReady: audi_ngw.form.vtpAjax.onAjaxModalContentReady",arguments);
	// execute funtions on new content
 	audi_ngw.form.vtpAjax._addEvents();
	
	// trigger event 
	audi_ngw.event.trigger('ajaxModalContentPrepared');
};

function STD(i,v) { 
	document.p.ixList.value = i;
	document.p.v.value = v;
	document.p.act.value = "offer";
	document.p.submit();
}

function nav_list(i) { 
	document.p.nav.value =i;
	document.p.act.value = "offer";
	
	if($('form').is('form.vtpAjax')) {
		document.p.action = "controller.content_fragment.do";
		$('form.vtpAjax').trigger('submit');
	}
	else
		document.p.submit();
}

function checkAction() {
	var ele = document.getElementsByName("act")[0].value;
	if (ele.length == 0)
		return false;
	else
		return true;  
}

function showCont(flag,id,id2) {
	var dsp=document.getElementById(id2).style.display;
	if (flag==1)
		document.getElementById(id).style.display = (dsp=="none")?"":"none";
	document.getElementById(id2).style.display = (dsp=="none")?"":"none";
	var nid = "N"+id;
	document.images[nid].src = (dsp=="none")?"img_vtp/arrow_bottom_7x4.gif":"img_vtp/arrow_right_4x7.gif";
	nid = "R"+id;
	var url = document.images[nid].src;
	var url2;
	if (dsp=="none")
		url2 = url.replace(/s.jpg/,"l.jpg");
	else
		url2 = url.replace(/l.jpg/,"s.jpg");
	document.images[nid].src = url2;
}

////////////////

/*
Zeigt eine Mouse-Over-Popup-Box an.

Verwendungsbeispiel:
onmouseover="showLargePic(this, '<div style=\'border:1px solid #000;\'><img src=\'%db02%\'></div>');" onmouseout="hideLargePic();"
*/
var largePic = null;
var largePicWhich = null;

function showLargePic(which, html, xOffset, yOffset)
{
	if (largePic != null)
	{
		document.body.removeChild(largePic);
		largePic = null;
	}

	which.onmousemove = function (e)
	{
		if (largePic == null)
		{
			var div = document.createElement("div");
			div.innerHTML = html;
			div.style.position = "absolute";
			div.style.zIndex = "100000";
			div.style.visibility= "hidden";
			largePic = document.body.appendChild(div);
		}

		var x, y;

		if (!e)
		{
			x = event.clientX + getScrollX();
			y = event.clientY + getScrollY();
		}
		else
		{
			x = e.pageX;
			y = e.pageY;
		}
		if (y + largePic.clientHeight > getScrollY() + getViewportHeight())
		{
			y = getScrollY() + getViewportHeight() - largePic.clientHeight;
		}

		x += (xOffset != undefined ? xOffset : 10);
		y += (yOffset != undefined ? yOffset : 0);

		largePic.style.left = x + "px";
		largePic.style.top = y + "px";
		largePic.style.visibility = "visible";
	};
}

function hideLargePic()
{
	if (largePic != null)
	{
		document.body.removeChild(largePic);
		largePic = null;
	}
}

function getScrollX()
{
	if (window.pageXOffset)
	{
		return window.pageXOffset;
	}
	else if (document.documentElement && document.documentElement.scrollLeft)
	{
		return document.documentElement.scrollLeft;
	}
	else if (document.body)
	{
		return document.body.scrollLeft;
	}
	else
	{
		return 0;
	}
}

function getScrollY()
{
	if (window.pageYOffset)
	{
		return window.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		return document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		return document.body.scrollTop;
	}
	else
	{
		return 0;
	}
}

function getViewportHeight()
{
	if (window.innerHeight)
	{	
		return window.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
	{
		return document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		return document.body.clientHeight;
	}
	else
	{
		return 0;
	}
}

/**
* Everything that needs to be done at onload needs to go here
*
* Constructor
* @method initialize
* @param {Object} oOptions
* @return {Void}
*/
audi_ngw.form.vtpAjax.initialize = function (oOptions){
	// cache 
	var scope = audi_ngw.form.vtpAjax;

	scope.__className =  'audi_ngw.form.vtpAjax';
	scope.__classVersion= '1.1';
	
	scope._oOptions = {};
	scope._oOptions._sClassNameMarker = 'vtpAjax'; // enables simple ajax on form
	scope._oOptions._sClassNameActiveMarker = 'runningRequest'; // marks form that requested the current XHR request

	// register ajaxModalContentReady event
	audi_ngw.event.bind('ajaxModalContentReady',audi_ngw.form.vtpAjax.onAjaxModalContentReady);
	audi_ngw.event.bind('ajaxPageLoadContentReady',audi_ngw.form.vtpAjax.onAjaxPageLoadContentReady);

	// add events 
	scope._addEvents();
};

function agb(url)
{  fenster=window.open(url, "Info","width=480,height=425,scrollbars=no,resizable=no,menubar=no,toolbar=no");
	self.focus;
}

/**
 * Every initialize function needs to go here, and only here!!!
*/
$(document).ready(function() {
	audi_ngw.vtp.statistic.initialize();
	audi_ngw.form.vtpAjax.initialize();
	audi_ngw.vtp.search.initialize();
	audi_ngw.vtp.list.initialize();
	audi_ngw.vtp.detail.initialize();
	// sagent initialize erfolgt nur beim Aufruf des SA
});

var currentModalId = new Object();
