
var Vote = function(){};
(function(){
	var instances 	= {};
	var constructs 	= {};
	var addMethod	= '';
	var templates	= {};
	var intervals	= {};

	// Vote
	Vote	= function(o, init){
		var o = $.extend(true, {}, o);
		if(isnull(init) || init){
			this.init(o);
		}
	};
	addMethod = Vote.prototype;

	/**
	 * init
	 */
	addMethod.init = function(o){
		var self		= this;

		this.url 		= '/vote/placevote.php';
		this.email 		= $('#emailaddress').val();
		this.$lb		= $('#leaderboard');
		this.instance	= randNum();
		this.school		= 1;
		this.templates	= {};
		this.$			= $('#vote'+this.school);

		$.extend(true, this, o);
		this.templates = $.extend(true, templates, this.templates);
	};

	/**
	 * updateDB
	 */
	addMethod.updateDB = function(school){
		if(!isnull(school)){this.school = school;}

		var self		= this;

		this.updateIconHtml(self.templates.loading);
		
		this.track();
		
		$.ajax({
			url 		: self.url,
			data		: {ajaxForm : 1, school : self.school, email : self.email},
			complete	: function(x){
				self.updateIconHtml(self.templates[x.responseText]);

				if(x.responseText=='error'){  }
				if(x.responseText=='success'){
					$('.toVoteOn').html(self.templates.toVoteOn);
				}
				
				
				$('.placevote:not(#vote-'+self.school+')').hide();
                                $('#emailaddress').hide();
				$('#vote-'+self.school).unbind('click.vote').bind('click.vote', function(){ 
				
					alert('Thank you for voting! We\'ve already registered your vote.');
				
					return false;
				});
				
				self.updateLeaderBoard();

			}
		});

		return true;
	};

	/**
	 * updateIcon
	 */
	addMethod.updateIconHtml = function(html){
		var self		= this;

		var $icon = $('#vote-'+self.school);
		$icon.html(html);

	};


	/**
	 * refreshLeaderBoard
	 */
	addMethod.refreshLeaderBoard = function(){
		var self		= this;
		intervals.leaderBoardInterval = setInterval(function(){
			self.updateLeaderBoard();
		}, 40000);
	};
	
	
	addMethod.updateLeaderBoard = function(){
		$.ajax({
			data : {ajaxForm : 1, rand : Math.floor(Math.random()*102312)},
			url : '/vote/rows.php',
			success : function(x){
				//if($('.leaderboardRows')!=x){
					$('.leaderboardRows').html(x);
				//}
			}
		});
	};
	
	addMethod.track = function(){
	
		$.getScript('http://www.google-analytics.com/ga.js', function(){
			try {
			var pageTracker = _gat._getTracker("UA-15984824-1");
			pageTracker._trackPageview();
			} catch(err) {}
		});

	};

	// TEMPLATES

	templates = {
		'success'	: '<img src="/images/voting/voteForMe-1.jpg" alt="Thank You For Voting!" />',
		'error'		: '<img src="/images/voting/voteForMe-3.jpg" alt="Too many votes placed from this browser session or IP address." />',
		'loading'	: '<img src="/images/voting/voteForMe-2.jpg" alt="Placing Vote" />',
		toVoteOn	: ''

	};

	// HELPER FUNCTIONS
	function randNum(p){
		if(isnull(p)){var p ='randNum';}
		return p+'-'+Math.floor(Math.random()*109129391291000);
	}

})();

$(function(){

	
	$('#nav a[n='+pagename+']').addClass('active');
	
	$('#nav a').rollfade({
		fadeIn : 1,
		fadeOut : 0.8,
		checkClass : 'active'
	});
	
	if($('#pagenav').length>0){
	
		$('#pagenav').scrollFollow({
			container : 'container',
			offset : 10,
			speed : 400
		});
	
	}
	
	// jQuery SmoothScroll | Version 09-11-02
	$('a[href*=#]').click(function() {
	
	   // duration in ms
	   var duration=1000;
	
	   // easing values: swing | linear
	   var easing='swing';
	
	   // get / set parameters
	   var newHash=this.hash;
	   var target=$(this.hash).offset().top;
	   var oldLocation=window.location.href.replace(window.location.hash, '');
	   var newLocation=this;
	
	   // make sure it's the same location      
	   if(oldLocation+newHash==newLocation)
	   {
	      // animate to target and set the hash to the window.location after the animation
	      $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
	
	         // add new hash to the browser location
	         window.location.href=newLocation;
	      });
	
	      // cancel default click action
	      return false;
	   }
	
	});
	
	
	
	if($('.placevote').length>0){
	
/*
		$.getScript('/js/jcCookieCheck.js?rand'+Math.floor(Math.random()*1203123), function(){
		
			var $ssn 	= $('.screenshots_n');
			var $m		= $('<div class="message" style="display:none">'+
			'<b style="color:red">Apologies. You need to have cookies enabled before you can vote.</b></div>').
			prependTo($('.purpleBorder'));

			var cookies = new jcCookieCheck({
				error	: function(){
					if($ssn.is(':visible')){
						$ssn.hide();
						$m.show();
					}
				},
				
				success	: function(){
					
					if($ssn.is(':hidden')){
						$ssn.show();
						$m.hide();
					}
					
				}
				
			});
		});
*/
	
		// voting
		$('.placevote').live('click.vote', function(){
			
			
			var $el = $(this);
			var id 	= $el.attr('id');
			id		= id.replace(/[^0-9]*/g, '');
			var v = new Vote();
			
			var title = $el.parent().find('.title').text();
			title = title.replace(/^\s+/, '');
			title = title.replace(/\s+$/, '');
			var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
			if($el.find('img').attr('src')!='/images/voting/voteForMe-1_hover.jpg'){
				if(emailPattern.test($('#emailaddress').val()) && $('#emailaddress').val().length){
                                    if(confirm('Are you sure you want to place a vote for "'+title+'"?')){
                                            v.updateDB(id);
                                    }
                                }else{
                                    if($('#emailaddress').val().length == 0){
                                        alert('Please enter an email address');
                                    }
                                    else{
                                        if(!emailPattern.test($('#emailaddress').val())){
                                            alert('Please enter a valid email address');
                                        }
                                    }
                                }
                        }
			
			
			return false;
		});
		
		$('.placevote img').live('mouseover', function(){
			var $el = $(this);
			
			var src = $el.attr('src');
			src = src.replace('.jpg', '_hover.jpg');
			
			$el.attr('src', src);
		});
		
		$('.placevote img').live('mouseout', function(){
			var $el = $(this);
			
			var src = $el.attr('src');
			src = src.replace('_hover.jpg', '.jpg');
			
			$el.attr('src', src);
						
		});
		
		var VOTE = new Vote();
		VOTE.refreshLeaderBoard();
		
	}
	
	$('.thankyouforvoting').live('mousedown', function(){
		alert('Thank you for voting! We\'ve already registered your vote.');
		return false;
	});
		
	
	
});
