/**
	@class
	@description .
*/
REFRESH_APP.ideasPage = {

	/**
		Onload call of the status controller.  Remove 'idea-notloaded' class and set to 'idea-notyetenabled'.  Change class of each
		idea returned status.  If sent ID not returned, enable idea (remove 'idea-notyetenabled' and set class to 'idea-notyetenabled').  
		If no votes left, disable all enabled ideas. 
		Remove show more button 
	*/
	onloadIdeasState: function(data,ids,votes,hasVoted) {
	
		if(hasVoted) REFRESH_APP.ideasPage.addFilterOption();
	
		var idsAr = ids.split(',');
		for(var i=0, len=idsAr.length;i<len;i++) {
			var id = idsAr[i];
			$('#idea-'+id).removeClass('idea-notloaded').addClass('idea-notyetenabled');
		}
		
		for(var i in data) {
			var idea = $('#idea-'+i);
			idea.removeClass('idea-notyetenabled');
			if(data[i] === 1) {
				// already voted
				REFRESH_APP.ideasPage.showVoteMsg(idea);
			} else if(data[i] === -1) {
				// don't show vote button, id invalid
			} else if(data[i] === 0) {
			 	// did not vote yet
				idea.addClass('idea-enabled');
			}
		}
		
		$('div.idea-notyetenabled').removeClass('idea-notyetenabled').addClass('idea-enabled');
		
		if(votes === 0) {
			$('div.idea-enabled').removeClass('idea-enabled').addClass('idea-disabled');
		}
		
		$('#load-more').show();
	
	},

	/**
		Get ideas state.  Send all idea ids with class 'idea-notloaded' to the status controller
	*/
	getIdeasState: function() {
	
		var ids = '';
		$('div.idea-notloaded').each(function() {
			var id = this.id;
			id = id.split('idea-').join('');
			ids+= id+',';
		});
		
		ids = ids.substr(0,ids.length-1);
		
		$('#load-more').hide();
		
		$.ajax({
			url: '/index/ajaxideasvoted',
			type: "POST",
			data: {ids:ids},
			dataType: "json",
			success: function(json){
				if(json.status === 'OK') {
					REFRESH_APP.statusBar.setCounter(json.leftVotesForToday);
					REFRESH_APP.ideasPage.onloadIdeasState(json.data,ids,json.leftVotesForToday,json.hasVoted);
				}
				if(json.status === 'ERROR') {
					// if not logged, enable all ideas
					$('div.idea-notloaded').removeClass('idea-notloaded').addClass('idea-enabled');
					$('#load-more').show();
				}
			},
			error: function() {
				// if ajax error, enable all ideas
				$('div.idea-notloaded').removeClass('idea-notloaded').addClass('idea-enabled');
				$('#load-more').show();
			}
		});		
	
	},

	/**
		Ideas load more 
	*/
	initLoadMore: function() {
	
		$('#load-more').live('click',function(e) {
		
			e.preventDefault();

			var sort = $('#ideas-select').val();
			if(!sort) sort = '';
			
			var href = this.href+'&sort=' + sort;
			
			$(this).addClass('loading');
			
			$.ajax({
				url: href+'&ajaxCalled=1',
				type: "GET",
				dataType: "html",
				success: function(html){
					$('#load-more').before(html).remove();
					REFRESH_APP.ideasPage.getIdeasState();
				},
				error: function() {
					$('#load-more').removeClass('loading');			
				}
			});
		
		});
	
	},
	
	/**
		If user is logged add filter option "Ideas you suppport" 
	*/	
	addFilterOption: function() {
	
		var select = $('#ideas-select');
		if(select.length < 1) return;
		if(select.hasClass('loaded')) return;
		select.addClass('loaded');
		select.append('<option value="2">'+filter_support+'</option>');

	},
	
	/**
		Ideas filter click event 
	*/	
	loadFilters: function(href) {
	
		$('#result-ideas').html('').addClass('loading');
		
		$.ajax({
			url: href+'&ajaxCalled=1',
			type: "GET",
			dataType: "html",
			success: function(html){
				$('#result-ideas').removeClass('loading').html(html);
				REFRESH_APP.ideasPage.getIdeasState();
			},
			error: function() {
				$('#result-ideas').removeClass('loading').html('<p class="load-more-error">'+error_occurred+'</p>');
			}
		});
	
	},

	/**
		Ideas filter menu 
	*/
	initFilters: function() {
	
		$('#ideas-select').change(function(e) {
		
			e.preventDefault();
			var href = $('#ideas-filter a.active').attr('href')+'&sort=' + this.value;
			REFRESH_APP.ideasPage.loadFilters(href);
		
		});
		
		$('#ideas-filter a').live('click',function(e) {
		
			e.preventDefault();
			
			var sort = $('#ideas-select').val();
			var href = this.href+'&sort=' + sort;
			
			$('#ideas-filter a').removeClass('active');
			$(this).addClass('active');
			
			REFRESH_APP.ideasPage.loadFilters(href);
		
		});
	
	},

	/**
		Load homepage flash header.  If it was already loaded, don't load again 
	*/
	initHeader: function() {
	
		if($('#home').length < 1) return;
	
		//show for french static header until french flash header available
		if($('body').hasClass('french')) {
			$.cookie("PEPSI_ONETIME_HEADER", 'true', { expires: 365 });
		}
		
		var isFirstTime =  $.cookie("PEPSI_ONETIME_HEADER");
		if(isFirstTime != null) return;

		$.cookie("PEPSI_ONETIME_HEADER", 'true', { expires: 365 });
		
		var url = '/swf/header.swf';
		
        if($('body').hasClass('french')) url = '/swf/header-fr.swf';
		
		var cl = $('#header-hero-flash h1').attr('class');
		var phase = Math.round(cl.replace(/[^0-9]/g, ''));
		
		var flashvars = {
			phase:phase
		};
		var params = {
			menu: "false",
			allowfullscreen: "true",
			allowscriptaccess: "always",
			wmode: "transparent"
		};
		var attributes = {
			id: "hero-flash",
			name: "hero-flash"
		};
		
		swfobject.embedSWF(url, 'header-hero-flash', '100%', '217', '9.0.0', '/video/expressInstall.swf', flashvars, params, attributes);	
	
	},

	/**
		Apply click event share links of the thank you popup
		Apply close click event to "No, thanks" link of the thank you popup
	*/
	initThanks: function() {
	
		$('p.thankyou-share a').live('click',function(e) {
		
			e.preventDefault();
			
			var obj = $(this);
			var parent = $(this).parents('.idea');
			
			var title = encodeURIComponent( msg_facebook );
			var href = thanksyou_site_url;
			
			if(obj.hasClass('idea-facebook')) {
				title = thanksyou_site_title;
				var win = 'http://www.facebook.com/sharer.php?u='+href+'&t='+title;
				window.open(win,'facebook_share','toolbar=0,status=0,width=626,height=436');
			}
			
			if(obj.hasClass('idea-twitter')) {
				var win = 'http://twitter.com/home?status='+title+' + '+href;
				window.open(win,"twitter_share_thanks");
			}

		});
	
		$('a.no-thanks').live('click',function(e) {
			e.preventDefault();
			$.fn.colorbox.close();
		});
	
	},

	/**
		Show thank you popup
	*/
	showThanks: function() {
	
		if($('#thankyou').length > 0) return;
	
		$.fn.colorbox({
			href:'/index/ajaxthankyou',
			scrolling:false,
			open:true,
			speed:300
		});
	
	},
	
	/**
		Apply mouseover/out event to all disabled ideas.  Shows a black bubble
	*/
	initDisabled: function() {
	
		$('div.idea-disabled .idea-button').live('mouseover',function(e) {
		
			var obj = $(this);
			var parent = obj.parent();
			var novote = $('div.idea-no-vote',parent);
			
			if( novote.length == 0 ) {
				novote = $('<div class="idea-no-vote">'+error_daily_limit+'<br /></div>');
				parent.append(novote);
				novote.show();
			} else {
				novote.show();
			}
			
		});
		
		$('div.idea-disabled .idea-button').live('mouseout',function(e) {
		
			var obj = $(this);
			var parent = obj.parent();
			var novote = $('div.idea-no-vote',parent);
			if( novote.length > 0 ) novote.hide();
		
		});

	},

	/**
		Apply click event to all idea's sharing links
	*/
	initSharing: function() {

		$('p.idea-share a').live('click',function(e) {
		
			e.preventDefault();
			
			var obj = $(this);
			var parent = $(this).parents('.idea');
			
			var title = encodeURIComponent( msg_twitter_vote +  parent.find('.monetary-tier').text() + ": "  + parent.find('.idea-content').text() );
			var href = escape( 'http://' + location.host + parent.find('.idea-link').attr('href') );
			
			if(obj.hasClass('idea-facebook')) {
				var win = 'http://www.facebook.com/sharer.php?u='+href+'&t='+title;
				window.open(win,'facebook_share','toolbar=0,status=0,width=626,height=436');
			}
			
			if(obj.hasClass('idea-twitter')) {
				var win = '/index/share#' + title + '||' + href;
				window.open(win,"twitter_share");
			}

		});

	},

	/**
		Start the sidebar video
	*/
	initVideo: function() {
		// set video
		var flashvars = {
			playerMode: "compact",
			staticFeed: "/video-data/get/xml"
		};
		if($('body').hasClass('french')) flashvars.staticFeed = "/video-data/french/xml";
		var params = {
			menu: "false",
			allowfullscreen: "true",
			allowscriptaccess: "always",
			wmode: "transparent"
		};
		var attributes = {
			id: "flashContent",
			name: "flashContent"
		};
		swfobject.embedSWF('/video/REPlayer.swf', 'about-player', '100%', '100%', '9.0.0', '/video/expressInstall.swf', flashvars, params, attributes);
		$('div.flash-disclaimer').removeClass('flash-disclaimer-hidden');
		REFRESH_APP.loadvideo.init();
	},
	
	/**
		Start the sidebar video
	*/	
	disableVote: function() {
		this.showThanks();
		$('.idea-enabled').removeClass('idea-enabled').addClass('idea-disabled');
	},
	
	/**
		Show vote random sucess message (Thanks! Gracias!)
	*/	
	showVoteMsg: function(parent) {
	
		parent.addClass('idea-voted');
		var obj = parent.find('.idea-share strong');
		var msgs = this.voteMessages;
		var msg = msgs[Math.floor(Math.random()*msgs.length)];
		obj.html(msg+'<br />');	
	
	},
	
	/**
		Vote onload callback.
	*/	
	onloadVote: function(json,parent) {
	
		/*
			{"status":"OK","data":{"leftVotesForToday":4}}
			{"status":"ERROR","errorCode":201,"errorMsg":"User voted for this idea today"}
			{"status":"ERROR","errorCode":202,"errorMsg":"User exceeded daily number of votes"}		
			{"status":"ERROR","errorCode":203,"errorMsg":"Not logged"}
			{"status":"ERROR","errorCode":200,"errorMsg":"Idea not valid for voting"}
		*/

		if(!parent.hasClass('idea-voting')) return;
		parent.removeClass('idea-voting');
		
		if(json.status === 'OK') {
		
			//Vote_Click();
		
			this.showVoteMsg(parent);
			var numVotes = json.data.leftVotesForToday;
			REFRESH_APP.statusBar.updateCounter(numVotes);
			if(numVotes == 0) this.disableVote();
			else REFRESH_APP.signUpPop.check();
			
			var ideaId = parent.attr("id").split('idea-').join('');
			pageTracker._trackEvent('User Submission', 'user vote', ideaId);
			
/*
			// analytics removed
			//spotlight tracking
			var axel = Math.random() + ""; 
			var a = axel * 1000000000000000000;	
			document.url = location.href;
			var doPing = new Image();
		
			// the URL below is a spotlight tag for page1
			doPing.src = REFRESH_APP.general.protocol + "ad.doubleclick.net/activity;src=2155040;type=2010s621;cat=prgvo125;ord="+ a + "?";
	
*/	
		}
		
		if(json.status === 'ERROR') {
		
			if(json.errorCode === 201) {
				this.showVoteMsg( parent );
				return;
			}
			if(json.errorCode === 202) {
				parent.addClass('idea-disabled');
				this.disableVote();
				return;
			}
			if(json.errorCode === 203) {
				parent.addClass('idea-enabled');
				REFRESH_APP.login.ajaxInit();
				pageTracker._trackEvent('Account', 'login step load - lightbox from vote');
				return;
			}
			
			parent.append('<span class="idea-error">'+error_connection_issue+'<br /></span>').addClass('idea-enabled');

		}
	
	},
	
	/**
		Idea vote button click event
	*/	
	ideaVote: function(e) {
	
		e.preventDefault();
		if(typeof e.button === 'undefined') return;		
		
		var id = this.id;
		var ideaId = id.split('vote-').join('');
		var obj = $(this);
		var parent = obj.parent();
		
		parent.find('span.idea-error').remove();
		
		if(parent.hasClass('idea-enabled')) {
			parent.removeClass('idea-enabled').addClass('idea-voting');
			$.ajax({
				url: '/vote/' + ideaId,
				type: "POST",
				data: { ok:true },
				dataType: "json",
				success: function(json){
					REFRESH_APP.ideasPage.onloadVote(json,parent);
					/* <!-- BEGIN AdPredictive pixel tag --> */
						try{var adpref=document.referrer==''?document.location:document.referrer;adpref=encodeURIComponent(adpref);}catch(e){var adpref='';}
						adp_px=new Image();
						adp_px.src = "http://pixel.adpredictive.com/adpredictive/app/com/pixel.php?campID=221&adpref="+adpref;
					/* <-- AdPredictive pixel tag --> */
				},
				error: function() {
					parent.append('<span class="idea-error">'+error_connection_issue+'<br /></span>').removeClass('idea-voting').addClass('idea-enabled');
				}
			});
		}
	
	},
	
	/**
		Vote sucess messages
	*/	
	voteMessages: msg_vote,
		
	/**
		Apply click/over/out event to all vote buttons
	*/			
	initVote: function() {
	
		var self = this;
		$('a.idea-button').live('click',self.ideaVote);
		$('a.idea-button').live('mousedown',function() {
			var obj = $(this);
			var parent = obj.parent();
			if(parent.hasClass('idea-disabled')) return;
			obj.addClass('idea-button-down');
		});
		$('a.idea-button').live('mouseup',function() {
			var obj = $(this);
			var parent = $(this).parent();
			if(parent.hasClass('idea-disabled')) return;
			obj.addClass('idea-button-down');
		});
		$('a.idea-button').live('mouseout',function() {
			var obj = $(this);
			obj.removeClass('idea-button-down');
		});
	
	},

	/**
		Initializes page
	*/
	init: function() {
	
		this.initLoadMore();
		this.initFilters();
		this.initSharing();
		this.initDisabled();
		this.initThanks();
		this.initVote();
		this.initVideo();
		this.initHeader();
		this.getIdeasState();

	}

};

jQuery(function($) {

	REFRESH_APP.ideasPage.init();

});


