/*
                    <div class="project" id="123">
                        <img src="/viewpoint/upload/demoImg.jpg"></img>
                        <div class="content">
                            <h1>TITLE</h1>
                            <span class="director">Dir: DIRECTOR</span> <span class="category">| Human interest</span>
                            <span class="releaseDate">01-01-2004</span>
                            <span class="story">
                                Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui
                            </span>
                        </div>
                    </div>
 
 */

vpClient.addMethods({
	
	initList : function(){
		waiter();
		this.template = '';
		if (!this.categories){
			// internal data has not been set up; do that:
			this.setupListVariables();
		}
		// determine filter
		var filterBy = this.currFilter.replace('filter', '');
		this.filterBy = filterBy.toLowerCase();

		var tmp = this.getNavigator(this.categories.get(this.filterBy));// get content & navigation (returned in an object)
		this.template = tmp.html;
		$('listContainer').update( this.template);
		$('listContainerNavigation').update(tmp.nav);
		$('listContainerNavigation').show();
		this.addProjectLinks();

		// initialize events on navigator
		$$('#listContainerNavigation .item').each(
			(function(elem){
				$(elem).observe('click', this.goToPage.bindAsEventListener(this));	
			}).bind(this)
		)
		
		// add cat-chooser
		$('contentHead').update("");
		var catLink = Builder.node('span', {id:'filterOngoing', className:'active'},['ongoing']);
		if ( (this.currFilter) && (this.currFilter != 'filterOngoing') ) catLink.className = 'inActive';	
		this.addEvent(catLink, 'click', this.filterList.bind(this));
		$('contentHead').appendChild(catLink);
		
		$('contentHead').appendChild(document.createTextNode('    '));
		var catLink = Builder.node('span', {id:'filterCatalogue', className:'inActive'}, ['catalogue']);
		if (this.currFilter == 'filterCatalogue')  {
			catLink.className = 'active';
		}
		this.addEvent(catLink, 'click', this.filterList.bind(this));
		$('contentHead').appendChild(catLink);
		this.showHideNavArrows();
		this.unWaiter();
	},
	
	setupListVariables : function(){
		this.projectLinks = new Array();
		// loop through DOM
		if (this.is_ie()){
			var first = this.DOM.childNodes.item(1);
		}else{
			var first = this.DOM.firstChild;
		}
		var categories = $H({});
		var projects = first.childNodes;
		$A(projects).each(
			(function(projectNode){
				if (projectNode.nodeName == 'product') {
					// check filter:
					var projectCategory = this.getProductProperty(projectNode, 'stage');
					if (!projectCategory) projectCategory = 'catalogue';
					if (!this.is_array(categories.get(projectCategory))) categories.set(projectCategory, new Array());
					categories.get(projectCategory).push(
						this.drawListProject(projectNode)
					)
				}	
			}).bind(this)
		)
		this.categories = categories;
	},

	addProjectLinks : function(){
		// add links to detail view for each project in list:
		$A(this.projectLinks).each(
			(function(pID){
				if ($(pID)){
					$(pID + '_readMore').observe('click', this.showProject.bindAsEventListener(this));
				}
			}).bind(this)
		);
	},
	
	goToPage : function(event){
		if (event.element().id == 'catalogueNext'){
			this.page++;
		}else if (event.element().id == 'cataloguePrevious'){
			this.page--;
		}else{
			this.page = parseInt(event.element().id);
		}
		var tmp = this.getNavigator(this.categories.get(this.filterBy));
		this.template = tmp.html;
		$$('#listContainerNavigation .item').each(
			(function(elem){
				if (parseInt(elem.id) == this.page){
					elem.className = 'item active';
				}else{
					elem.className = 'item';
				}
			}).bind(this)
		)
		$('listContainer').update( this.template);
		this.showHideNavArrows();
		this.addProjectLinks();
	},

	showHideNavArrows : function(){
		if ($$('#listContainerNavigation .item').length == 2){
			$('catalogueNext').hide();
			$('cataloguePrevious').hide();
			return;
		}
		if (this.page < ($$('#listContainerNavigation .item').length -3 ) ){
			$('catalogueNext').show();
		}else{
			$('catalogueNext').hide();
		}		
		if (this.page < 1){
			 $('cataloguePrevious').hide();
		}else{
			 $('cataloguePrevious').show();
		}
		placeFooter();
	},

	getNavigator: function(arr){ 
		var idxStart = (this.page * this.itemsPerPageList);
		var idxEnd = idxStart + this.itemsPerPageList ;
		var idx = 0;
		var nav ='';
		var html='';
		var page = 0;
		$A(arr).each(
			(function(segment){
				if ((idx % this.itemsPerPageList) == 0){
					nav+= '<span ';
					if (page != this.page){
						nav += ' class="item" ';
					}else{
						nav += ' class="item active" ';
					}
					nav+= ' id="' + page+'_listNavItem">' +(page+1) +' | </span>';
					page++;
				}

				if ((idx >= idxStart)&&(idx < idxEnd)){
					html+=segment;
				}
				idx++;
			}).bind(this)
		)
		nav += '<span class="item" id="catalogueNext"> > </span>'
		nav = '<span class="item" id="cataloguePrevious"> < </span>' + nav;
		return { 'nav' :  nav, 'html' : html}
	},

	drawListProject : function(node){
		// get values from node:
		var pID = wps.dom.getElementValue(node.getElementsByTagName('product_id').item(0));
		var title = this.getProductProperty(node, 'name');
		var category = this.getProductProperty(node, 'category');
		var story = this.getProductProperty(node, 'story');
		
		var director = this.getProductProperty(node, 'Director');
		var year = this.getProductProperty(node, 'Year');
		
		var images = this.getChildObjectByName(node, 'media');
		var imgData = this.getFirstImage(images[0]);
		var imgHTML = imgData.get('imgHTML');
		var height = imgData.get('height');
		if (!height || height < 100) height = 150;
		height = (parseInt(height) + 20);
		
		var template = '';
		template += '<div class="project" id="' + pID + '" style="height:' + height + '">';
		template += imgHTML;
		template += '<div class="content">';
		template += '<h1>' + title + '</h1>';
		if (director) template += '<span class="director">' + director + '</span>|';
		if (category) template += '<span class="category"> ' + category + '</span>';
		if (year) template += '<span class="releaseDate">' + year + '</span>';
		if (story) template += '<br/><span class="story">'  +story.substr(0, 300) + '...</span>';
		template += '</div>';
		template += '<span id="' + pID + '_readMore" class="projectLink" > read  more</span>';
		template += '</div>';
		//var projectLink = Builder.node('span', {className:'projectLink', id:pID}, [" [Read more]"]);
		//$(projectLink).observe( 'click', this.showProject.bind(this));
		this.projectLinks.push(pID);
		return template;
	},
	
	hiliteListItem: function(event){
		var elem = Event.element(event);
		elem.style.backgroundColor = 'green';
	},
	
	unhiliteListItem: function(event){
		var elem = Event.element(event);
		elem.style.backgroundColor = 'black';
	},
	
	getFirstImage : function(node){
		var imgID = '';
		var extension = '';
		var filename = '';
		var width = '';
		var height = '';
		//if (!filename) return '<div class="images"></div>';
		$A(node.childNodes).each(
			(function(childNode){
				if (childNode.nodeName == 'property'){
					var key = wps.dom.getElementValue(childNode.getElementsByTagName('key').item(0));
					if ( (key != 'name') && (imgID =='' ) ) {
						imgID = wps.dom.getElementValue(childNode.getElementsByTagName('property_id').item(0));
						filename = wps.dom.getElementValue(childNode.getElementsByTagName('fileName').item(0));
						var sizes = childNode.getElementsByTagName('size');
						if (sizes.length > 0){
							var thumb = filename.substring(0,(filename.length-4)) + '190.' + filename.substring((filename.length-3) , filename.length);
							$A(sizes).each(
								function(sizeNode){
									if (sizeNode.getAttribute('file') == thumb){
										width = sizeNode.getAttribute('width');
										height =  sizeNode.getAttribute('height');
									}
								}
							)
						}
						if (filename) extension = filename.substr( (filename.length - 3), filename.length);
					}
				}
			}).bind(this)
		)

		if (imgID){
			if (extension == 'flv'){
				var html = '<img style="display:none;" src="&amp;action=objectWeb&amp;rpc=1&amp;subAction=getCachedBin&amp;propID='+ imgID+ '">';
				html+= '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" style="z-index: 99;" data="wpsRepos2/lib/3rd/flashPlayer/flvplayer.swf" type="application/x-shockwave-flash" height="135" width="190">'
				html+= '<param value="#FFFFFF" name="bgcolor">';
				html+= '<param name="movie" value="wpsRepos2/lib/3rd/flashPlayer/flvplayer.swf">';
				html+= '<param name="flashvars" value="file=/upload/objectweb/' + imgID + '.flv&showdigits=true&autostart=false&displayheight=162&image=http://' + window.location.hostname + gRelRootPath + '_wpsTemp/' + filename + '1.jpg">';
				html+= '<param name="allowScriptAccess" value="sameDomain">';
				html+= '<embed src="wpsRepos2/lib/3rd/flashPlayer/flvplayer.swf" quality="high" bgcolor="#ffffff" wmode="transparent" style="z-index: 99;" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="file=/upload/objectweb/' + imgID + '.flv&showdigits=true&autostart=false&;displayheight=162" height="162" width="190">';
				html+= '</object>';
			}else{
				if (filename){
					var thumb = filename.substring(0,(filename.length-4)) + '190.' + filename.substring((filename.length-3) , filename.length);
					//var imgURI = this.getURI() + '&action=objectWeb&rpc=1&subAction=getBin&propID=' + imgID;
					//var html = '<img style="display:none;" src="&amp;action=objectWeb&amp;rpc=1&amp;subAction=getCachedBin&amp;propID='+ imgID+ '&amp;resizeWidth=190">';
					var html ='';
					html += '<img id="' + imgID + '" src="/upload/objectweb/' + imgID + '_190.jpg" class="projectImage"></img>';
				}else{
					var html = '<img src="/viewpoint/upload/demoImg.jpg"></img>';
				}
			}
		}else{
			var html = '<img src="/viewpoint/upload/demoImg.jpg"></img>';
		}
		var out = new Hash({});
		out.set('imgHTML', '<div class="images">' + html + '</div>');
		out.set('width', width);
		out.set('height', height);
		return out;
	},
	
	filterList : function(event){
		if (event) {
			var elem = Event.element(event);
			var filterBy = elem.id;
			this.currFilter = filterBy;
		}
		this.waiter();
		this.page = 0;
		this.view = 'list';
		this.initView();
		this.initList();
	},
	
	showProject : function(event){
		var elem = Event.element(event);
		var productID = elem.id;
		
		var wpsRPC = new wps.rpc;
		wpsRPC.debug = true;
		wpsRPC.attachWaiter(this.waiter, this);
		wpsRPC.attachUnWaiter(this.unWaiter, this);
		wpsRPC.createCall('vpClient', this.initProjectView.bind(this), this);
		wpsRPC.call('getChildObjects', 'parentObjectID=' + parseInt(productID), 'isIE=' + this.is_ie());
	},
	
	initProjectView : function(req){
		var DOM = req.responseXML;
		this.currProjectNode = DOM.getElementsByTagName('product').item(0);
		this.view = 'detail';
		this.initView();
	}
	
});