/**
 * AUDI JavaScript library: Creates <select onchange="audi_ngw.dom.select.change"><option value="HREF"> from <ul><li><a>  and sets onchange event to control iframe 
 * 
 * @projectDescription	Creates <select onchange="audi_ngw.dom.select.change"><option value="HREF"> from <ul><li><a>  and sets onchange event to control iframe 
 * @namespace			dom
 *
 * @author 				$Author: hhoettecke $
 * @version				$Revision: 4452 $
 * @copyright			NEUE DIGITALE GmbH, Berlin
 * 
 * @jslint: 2008-10-31
 * 
 * @file:				audi_ngw.dom.select.js
 * $URL: https://svn.pvtool.org/svn/day_audi_ngw/trunk/ngw_base/frontend/js/audi/audi.dom.select.js $
 */

/* create namespace */
audi_ngw.namespace(audi_ngw,'dom.select');


/* CREATE JQUERY PLUGINS */
/**
 * @see audi_ngw.dom.select._doCreate
 */
$.fn.audi_anchorsToOptions = function() {
	this.each(function (){
		audi_ngw.dom.select._doCreate(jQuery(this));
	});
  return this;
};


 /**
 * Replaces HTML ul.to_select li a[href=HREF] with select option[value=HREF], copies ul class/id to select-element Bridges to _doCreate()
 * @see _doCreate()
 * @param {Object} element
 * @return {Void}
 */
audi_ngw.dom.select.create = function(element){
	audi_ngw.dom.select._doCreate(jQuery(element));
};

/**
 * Replaces HTML ul.to_select li a[href=HREF] with select option[value=HREF], copies ul class/id to select-element
 * @param {Object} jQuery extended element
 * @private
 * @return {Void}
 */
audi_ngw.dom.select._doCreate = function ($element) {
	
	if (!$element.size()) {return this; }
	
	// cache scope
	var scope = audi_ngw.dom.select;
	
	// get html string, create element
	var _$newOption = jQuery(scope._options.sHTMLOption);
	var _sId = $element.attr('id');
	// get html string, create element, copy attributes, remove marker class, set change event
	var _$sHTMLSelect = jQuery(scope._options.sHTMLSelect)
		.attr('id', _sId)
		.attr('className', $element.attr('className'))
		.removeClass(scope._options.sClassNameMarker)
		.change($element.metadata().to_select.onChange);

	// cylce all anchors clone html template, set attributes, append to select, replace source element
	$element
		// create options, append them to _$sHTMLSelect
		.find('li a').each(function() {
			var _$link = jQuery(this);
			var _sMeta = '';
//			// copy .rel to {{type:options}}
//			if (_$link.attr('rel')) {
//				var _aCn = _$link.attr('class').split('}');
//				if (_aCn.length > 1) {
//					_aCn[_aCn.length - 2] = ", { type :'popup'} ";
//					_sMeta = _aCn.join('}');
//				} else {
//					_sMeta = _aCn.join(' ')+"{ type :'popup'} ";;
//				}
//			}
//			else {
//				_sMeta = _$link.attr('class');
//			}
//			console.log(_$link.attr('rel'),':\n',_$link.attr('class'), "\n" , _sMeta)
			// set properties
			_$newOption
				.clone(true)
				.attr('value', _$link.attr('href'))
//				.attr( ( (jQuery.browser.safari) ? 'class' : 'selected'  ) , ( (jQuery.browser.safari) ? 'selected' : 'selected' ) )
//				.attr('class',_sMeta)
				.attr('class',_$link.attr('class'))
				.text(_$link.text())
 				.appendTo(_$sHTMLSelect);
		});
		// handle preselection
		// add options "audi_ngw.dictionary.OPTION_CHOOSE" if nothing's preselected
		if (!_$sHTMLSelect.find('.selected').size()) {
			_$newOption
				.clone(true)
				.attr('value', '')
				.attr('class', 'selected' )
				.text(audi_ngw.dictionary.OPTION_CHOOSE)
 				.prependTo(_$sHTMLSelect);
		}
		
		// set selection from classname, can't set on creation of option due to safari bug (needs parents)
		 _$sHTMLSelect.find('.selected').attr('selected', 'selected').removeClass('selected');

		// replace <ul>-element with the created <select>-element
		$element
			.replaceWith(_$sHTMLSelect);

		// fire onchange event to initialize state if flag is set and the selected element has a value
		if (_$sHTMLSelect.metadata().to_select.bTrigger === true && _$sHTMLSelect.find('option[selected]').attr('value')) {
			_$sHTMLSelect.triggerHandler('change');
		}

	// free memory
	_$sHTMLSelect = null;
	_$newOption = null;

	return this; 
};



/**
 * Replaces HTML ul.to_select li a[href=HREF] with select option[value=HREF], copies ul class/id to select-element. Ul will be grabbed below by the optional argument id || document.body.
 * @param {String} (Wrapper id)
 * @private
 * @return {Void}
 */

audi_ngw.dom.select.createOn = function(sIdParent){
	// set environment
	var _sSelector;
	var scope = audi_ngw.dom.select;
	// construct selector
	if (sIdParent) {
		_sSelector = "#";
		_sSelector += sIdParent;
		_sSelector += ' ul.';
		_sSelector += scope._options.sClassNameMarker;
	} else {
		_sSelector = 'ul.';
		_sSelector += scope._options.sClassNameMarker;
	}
	// add html nodes
	jQuery(_sSelector).audi_anchorsToOptions();
};

/**
 * 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.dom.select.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("-> "+audi_ngw.event.ajaxModalContentReadyCount+" EVENT - ajaxModalContentReady:audi_ngw.dom.select.onAjaxModalContentReady",arguments);
	// execute funtions on new content
 	audi_ngw.dom.select.createOn(audi_ngw.url.getContentId());

	// trigger event 
	audi_ngw.event.trigger('ajaxModalContentPrepared');
};


/**
 * Custom Event: wil be fired as soon as we injected the xhr-snippet 
 * @param {Object} event
 * @param {Object} data {sId: new HTML parent Id}
 */
audi_ngw.dom.select.onAjaxSnippetReady = function(event,data){
 
	//audi_ngw.log("EVENT - ajaxSnippetPrepared: audi_ngw.dom.select.onAjaxSnippetReady",arguments);
	// execute funtions on new content
	audi_ngw.dom.select.createOn(data.sId.slice(1));
	
	// trigger event 
	audi_ngw.event.trigger('ajaxSnippetPrepared');
};

/**
 * Initialize 
 * @method initialize
 * @constructor
 * @param {Object} Options 
 * @return {Void}
 */
audi_ngw.dom.select.initialize = function(){
	
	this.__className =  'audi_ngw.dom.select';
	this.__classVersion= '1.2';
	
	
	this._options = {};
	this._options.sHTMLSelect ='<select></select>';
	this._options.sHTMLOption ='<option value="HREF"></option>';
	this._options.sClassNameMarker = 'to_select';
	this._sIdIFrame= '#audi_iframe';
	audi_ngw.dom.select.createOn('audi_content_wrapper');
	
	// register ajaxModalContentReady event
	audi_ngw.event.bind('ajaxModalContentReady.domSelect',audi_ngw.dom.select.onAjaxModalContentReady);
	audi_ngw.event.bind('ajaxSnippetReady',audi_ngw.dom.select.onAjaxSnippetReady);


};
