﻿
/**
  * KIM.template 
  * 
  * @description
  * Microsoft Live Messenger Portal frontend templating engine.
  
  * 
  * @copyright       Neue Digitale / Razorfish 
  * @author          martin.krause@neue-digitale.de
  * @version         1.3
  *
  * @revision        $Revision$
  * @lastmodified    $Date$
  *
  * @jslint			  2009-03-03
  *
  */

if (typeof(KIM) == 'undefined') { KIM ={};} 
KIM.template = {
	
	__version: 1.3, // class version 
	__class: 'KIM.template', // class name
	 
	// set default options
	_oDefaults: {
    },
 
	 
	/**
	 * Setup
	 * @param {String} [sTitle], title
	 * @return {Void}
	 */
	_setUp: function (oOptions) {
		var _scope = KIM.template;
		// merge options and defaults
		_scope._oOpt = $.extend({},_scope._oDefaults, oOptions);
		_scope._oDefaults = null;
	},
	
	/**
	* Fills json data into HTML-Template
	* @param {String||jQuery-Object}  Selector / Object narrowing scope
	* @param {String} sType: repeater
	* @param {Object} oData, json-encoded data
	* @return {Void}
	*/
	fill: function ($scope, sType, oData, oOptions_) {
	    
	    var $scope = jQuery($scope);
	    
	    switch (sType) {
	    
//	        case 'single':
//	            $scope.html(oData[0]);
//	        break;
	        
	        case 'repeater':
				KIM.template._doFillOnRepeater($scope,oData, oOptions_);
	        break;
	        
	        default:
	        break;
	    }
	    
	},
	 
	/**
	* Fills every .template_item below .template_repeater with the corresponding JSON.property 
	* e.g. alt="Title" will be filled with json.item.Title
	* @param {String} sType: repeater
	* @param {Object} oData, json-encoded data
	* @return {Void}
	*/	
	_doFillOnRepeater: function ($scope,json_,oOptions_) {
	    var iPaginate = iPaginate || null
		var _$elRepeater = $scope.find('.template_repeater');
		// clone templates	        
		var _$htmlCloneRepeater = _$elRepeater.clone(true);
		var _$htmlTemplateItem = $scope.find('.template_repeater li');
        //var _$htmlTemplateItem = jQuery(_$htmlCloneRepeater.eq(0).html());
        // clear wrapper
        _$htmlCloneRepeater.empty();
        
        // handle pagination
        if (oOptions_.iPaginationItems !== null && oOptions_.iPaginationSite) {
			// shrink json object to current page
			var _$reducedJSON = KIM.template.getPaginationJSON (json_,((oOptions_.iPaginationSite -1)* oOptions_.iPaginationItems), ((oOptions_.iPaginationSite * oOptions_.iPaginationItems)-1));
        }
        
        // cycle json data
        jQuery(_$reducedJSON).each(function (index,oItem) { 
 
			// clone item
			var _$htmlCloneItem = _$htmlTemplateItem.clone(true);

				//get html element that need a click-event
				var _$elements = jQuery(_$htmlCloneItem).find('.template_clickApplicationID');
 
				_$elements
					.unbind('click.applicationId')
					.bind('click.applicationId',{_sId:oItem['ApplicationID']},KIM.template.showGamesById);

				// construct marker class
				var _sMarkerClass = '.template_item';
				
				//get html element
				_$elements = jQuery(_$htmlCloneItem).find(_sMarkerClass);
				
				// skip everything if there's no element
				if(!_$elements.size()) { return false;}
				
				_$elements.removeClass(_sMarkerClass.slice('1'));
				
               				 
					 _$elements
						// handle images 
						.filter('img')
						.each( 
							function (k,element) {
							
								var _$element = jQuery(element);
		                        
		                        
		                        
								// set src if necessary (_$element.src == template_insert_Rating ||template_insert_ImageUrl)
								var _sAttr = _$element.attr('src');
								
								// rating image 
								if ( _sAttr.indexOf('ating') !== -1 ) {
									_$element
										// contruct rating image 
										.attr('src', '/images/icons/rating'+oItem['Rating']+'.gif');
						
								} 
								// simple image
								if (_sAttr.indexOf('ImageUrl') !== -1) {
									_$element
										// add source
										.attr('src', oItem['ImageUrl']);
								}
								
								// set title if necessary (_$element.title == any JSON Object property)
								_sAttr = _$element.attr('title');
								if (oItem[_sAttr]) {
									_$element.attr('title',oItem[_sAttr].toString());
								}												
								
								// set alt if necessary( _$element.alt == any JSON Object property)
								_sAttr = _$element.attr('alt');
								if (oItem[_sAttr]) {
									_$element.attr('alt',oItem[_sAttr].toString());
								}												
							}
						)
						.end()
						// remove images 
						.not('img')
						// handle anchors
						.filter('a')
						.each( 
							function (k,element) {
								var _$element = jQuery(element);
								
								// tracking							
								if(_$element.hasClass("trackingPlayNow")) {
								    _$element.bind("click.tracking",{trackingString: "M_SpielStarten_"+oItem['Nwert']},KIM.template._tracking);
								}
								if(_$element.hasClass("trackingImage")) {
								    _$element.bind("click.tracking",{trackingString: "M_SpielStartenBild_"+oItem['Nwert']},KIM.template._tracking);
								}
								if(_$element.hasClass("trackingTitle")) {
								    _$element.bind("click.tracking",{trackingString: "M_SpielStartenTitel_"+oItem['Nwert']},KIM.template._tracking);
								}
								if(_$element.hasClass("trackingMoreInfo")) {
								     _$element.bind("click.tracking",{trackingString: "M_MehrInfos_"+oItem['Nwert']},KIM.template._tracking);
								}
									
								if(_$element.hasClass("jLoadDetailByIndex")) {
								     _$element.attr('href', (_$element.attr('href')+oItem['Id'].toString()) );
								     return true;
								}											
								
								// set title if necessary (_$element.title == any JSON Object property)
								var _sAttr = _$element.attr('title');
								if (oItem[_sAttr]) {
									_$element.attr('title',oItem[_sAttr].toString());
								}	
								
								// set href if necessary (_$element.href == any JSON Object property)
								 _sAttr = 'Link';
								 //_$element.attr('href'); // ie creates absolute urls
								
								if (oItem[_sAttr]) {
									_$element.attr('href',oItem[_sAttr].toString());
								} else {
									if (_$element.hasClass('template_requires_href')) {
										_$element.remove();
									}
								}
								
								// set .text () if necessary (_$element.text() == any JSON Object property)
								 _sAttr = _$element.text();
								if (oItem[_sAttr]) {
									_$element.text(oItem[_sAttr].toString());
								}
								
								// remove <anchor> in there's no href="Link" value and it's required
								if (_$element.hasClass('template_requires_href') ) {
								//console.log(_$element.attr('href'))
								}
//								if (_$element.hasClass('template_requires_href') ) {
//								alert(_$element.attr('href') + ' <> ' + _$element.attr('href').toString().indexOf('Link'))
//								}
//								if (_$element.hasClass('template_requires_href') && _$element.attr('href').toString().indexOf('Link') !== -1) {
//									_$element.css('color','red');
//								}
								
							}
						)
						.end()
						// remove anchors
						.not('a')
						// remaining elements
						.each( 
							function (k,element) {
							
								var _$element = jQuery(element);
								
								// set title if necessary (_$element.title == any JSON Object property)
								var _sAttr = _$element.attr('title');
								if (oItem[_sAttr]) {
									_$element.attr('title',oItem[_sAttr].toString());
								}	
								
							 	// set .text () if necessary (_$element.text() == any JSON Object property)
								 _sAttr = _$element.text();
								if (oItem[_sAttr]) {
									_$element.text(oItem[_sAttr].toString());
								}

								if (_$element.hasClass('template_date') && oItem['StartDate']) {

									var myregexp = /\/Date\((.*?)\)/;
									var match = myregexp.exec(oItem['StartDate']);
									var _date = new Date( parseInt(match[1]) );
									var _sDate = _date.getDate() + '.'+(_date.getMonth()+1) +'.'+(_date.getFullYear());
									
									_$element.text(_$element.text()+_sDate)

					            }
					            
					            if (_$element.hasClass('template_date') && oItem['PublishDate']) {

					                var myregexp = /\/Date\((.*?)\)/;
					                var match = myregexp.exec(oItem['PublishDate']);
					                var _date = new Date(parseInt(match[1]));
					                var _sDate = _date.getDate() + '.' + (_date.getMonth() + 1) + '.' + (_date.getFullYear());

					                _$element.text(_$element.text() + _sDate)

					            }
								
							}

						);
				 
 
			// append each item to our new repeater-wrapper
			_$htmlCloneRepeater.append(_$htmlCloneItem);
        });

		

		
       // prepare cloned wrapper for appending 
        _$htmlCloneRepeater
			.removeClass('template_repeater')
			.addClass('generated_repeater')
			// fix wired ie bug 
			.show()
			.css('display','block');
        // append cloned wrapper behind original wrapper
		_$elRepeater.after( _$htmlCloneRepeater);
		
		KIM.template.createPagination(oOptions_.iPaginationSite,oOptions_.iPaginationItems,json_.size());
		
		_$elRepeater = null;
		_$htmlCloneRepeater = null;
		_$htmlTemplateItem = null;
		// force redraw
		if(jQuery.browser.msie) {
			window.setTimeout(function () {
				jQuery('.generated_repeater')
					.show()
					.css('display','block')
					.css('border','1px solid red')
					.css('border','none');
				},100);
		}
	  },
	
	/**
	* Creates pagination json by slicing the necessary elements from passed object
	* @param {JSON}
	* @param {Number} Index: Start
	* @param {Number} Index: End 
	* @return {JSON} Sliced elements
	*/
	getPaginationJSON: function (json_,_iFrom,_iTo) {
		// create temp json 
		var _reducedJSON = [];			
			// cycle	
			for(var _i = _iFrom; _i <= _iTo; _i++) {
				// copy if possible
				if (json_[_i]) {
					// order elements
					_reducedJSON[_reducedJSON.length] = json_[_i];
				}
			}
		// return 
		return _reducedJSON;
	},
	
	
	/**
	* Creates pagination html
	* @param {Number} Current page
	* @param {Number} Items per paginated page 
	* @param {Number} Max number of items to paginate
	* @return {Void} 
	*/
	createPagination: function (iCurrentPage_,iItemsPerPage_,_iMaxItems) {

		// create pagination
		jQuery('.pagination').remove()
		var _$ul = jQuery('<ul class="pagination">');
		var _iSpan = 2;
		var _iTo = (iCurrentPage_ + _iSpan);
		var _iFrom = iCurrentPage_-_iSpan ;
		var _iMaxPages = Math.ceil(_iMaxItems/iItemsPerPage_)
		var _bSkippingFront = false;
		for(_i = _iFrom; _i <= _iTo  ; _i++) {
		
			// skip invalid values
			if (_i < 1 || _i > _iMaxPages) {continue;}
		
		
			// add skipping to the beginning
			if ( _iFrom >= 0 && !_bSkippingFront ) {
				KIM.template._createPaginationItem(_$ul,'first',1);
				KIM.template._createPaginationItem(_$ul,'previous',( ( (iCurrentPage_-1) > 0 ) ? (iCurrentPage_-1) : 1 ) )	;
				_bSkippingFront = true;
			}
			
			// add ellipses to the beginning
			if ( (_i >= 2 && _i == _iFrom) ) {
				KIM.template._createPaginationItem(_$ul,'…',null);
			}
			
			// create numbered items 	
			if ( _i === iCurrentPage_ ) {
				KIM.template._createPaginationItem(_$ul,_i,'active');
			}
			else {
				KIM.template._createPaginationItem(_$ul,_i,_i);
			}


		}
		
		// add ellipses to the end
		if ( (iCurrentPage_ < (_iMaxPages-_iSpan)) ) {
			KIM.template._createPaginationItem(_$ul,'…',null);
		}

		// add skipping to the end
		if ( iCurrentPage_ < (_iMaxPages)) {
			KIM.template._createPaginationItem(_$ul,'next',(iCurrentPage_+1));
			KIM.template._createPaginationItem(_$ul,'last',_iMaxPages);
			
		}
		

		
		// append to .generated_repeater
		jQuery('.generated_repeater').after(_$ul)
		
		jQuery('ul.pagination').css({
			position: 'absolute'
			})
		jQuery('ul.pagination').css({
			left: '50%',
			marginLeft: -(_$ul.width()/2)+'px'
			
		});
		
	},
	
	
	/**
	* Creates a single pagination html item 
	* @param {HTMLNode} Parent element
	* @param {String || Number} Textvalue
	* @param {String} on click action-marker, being passed as event.data
	* @return {Void} 
	*/
	_createPaginationItem: function ($elParent_,sText_,sAction_) {
 
		// create active element 
		if (sAction_ == 'active') {
			$elParent_ 
			.append(
				jQuery('<li class="'+sAction_+'">')
				.text(sText_)
			);
			return true;
		} 

		// create elements with sText as classname, e.g. "first" / "last"
		if (typeof(sText_) == 'string' && sText_.length > 2) {
			$elParent_ 
			.append(
				jQuery('<li class="'+sText_+'">')
				.append(
					jQuery('<a href="/"></a>')
					.text(sText_)
					.bind('click.pagination',{sAction: sAction_},KIM.load.showPaginatedPage)
				)
			);
			return true;
		} 
		
		
		// create link element
		if (sAction_) {
			$elParent_ 
			.append(
				jQuery('<li>')
				.append(
					jQuery('<a href="/"></a>')
					.text(sText_)
					.bind('click.pagination',{sAction: sAction_},KIM.load.showPaginatedPage)
				)
			);
			return true;
		} 
		
		// create ellipses
		$elParent_ 
		.append(
			jQuery('<li>')
			.text(sText_)
		);
		return true;
	
	},
	
	
	/**
	* Tracking
	* @param {Event}
	* @return {Bool} false 
	*/
	_tracking: function (event){
		KIM.tracking.gimasTracking(event.data.trackingString);
	},
	
	
	
	/**
	* Helper for showing games by their json.ApplicationID
	* @param {Event}
	* @return {Bool} false 
	*/
	showGamesById: function (event){
		event.stopPropagation();
		if (jQuery.browser.msie) { KIM.messengerapi.openMessengerApplicationByID(event.data._sId); return false;}
		return false;
	},
	
	 /**
	 * Constructor
	 * @param {Object} [oOptions]
	 * @constructor
	 */
	initialize: function (oOptions) {
		// fake singleton
		if (this._oOpt) {
			return this;
		}
		// setup 
		this._setUp(oOptions);
		// fake singleton
		return this;
	}
};

// initialize onDOMReady
$(function() {
	KIM.template.initialize();
});

