/**
 * script for vote system
 * customer: Steven
 * author: Derick Koo from ConRic Consultancy
 * All rights reserved by Steven and Pimp Empires
 */
var Vote = {
	/**
	 * Some constants used in this vote system
	 */
	CONS: {
		VOTE_LABEL_AVAILABLE: 'Vote',
		VOTE_LABEL_DISABLE: 'Thank you ...',
		VOTE_LABEL_VOTING: 'Voting ...',
		SUCCESS_MSG: 'Your account has been credited! Thanks You',
		NONSUCCESS_MSG: 'Some error occurred on the server! you account may not be credit correctly, try to refresh this page to fix this problem!',
		FAILURE_MSG: 'Vote not completed, your account will not be credited',
		BLOCKED_MSG: 'Sorry, Your browser blocked popup window from Pimp Empires, kindly check and click the vote button again!',
		VOTE_URL: '/game/success_vote.php'
	},
	
	/**
	 * Vote.Link class
	 */
	Link: function(siteDesc, turns, linknum, site, link, pid, timer) {
		this.siteDesc = siteDesc;
		this.turns = turns;
		this.linknum = linknum;
		this.site = site;
		this.link = link;
		this.pid = pid;
		this.timer = timer;
	},
	
	/**
	 * method used to render Vote.links to the webpage
	 */
	renderLinks: function() {
		if (Vote.links == null || Vote.links.length == 0) {
			document.getElementById('list').innerHTML = '<li>No available vote link</li>';
			return;
		}
		var p = '<li><div>'
		        +  '<div class="Entry">#SITEDESC</div>'
		        +  '<div class="VoteBtn">#TURNS Turns<button onclick="Vote.openVote(this, #LINKNUM, \'#SITE\', \'#LINK\', #PID, #TIMER, #USEFRAME);">Vote</button></div>'
		        +  '<div class="Clear" />'
		      + '</div></li>';
		 var result = '';
		 for (var i = 0; i < Vote.links.length; i++) {
		 	var v = Vote.links[i];
		 	var l = p.replace(/#SITEDESC/, v.siteDesc)
		 	    .replace(/#TURNS/, v.turns)
		 	    .replace(/#LINKNUM/, v.linknum)
		 	    .replace(/#SITE/g, v.site)
		 	    .replace(/#LINK/, v.link)
		 	    .replace(/#PID/, v.pid)
		 	    .replace(/#TIMER/, v.timer)
		 	    .replace(/#USEFRAME/, v.useFrame);
		 	result += l;
		 }
		 document.getElementById('list').innerHTML = result;
	},
	
	/**
	 * when player click Vote button, invoke this method to begin vote process
	 * it will check whether the vote window opened or not first
	 */
	openVote: function(btn, linknum, site, link, pid, timer) {
		if (window.processingLink != null) {
			alert('You can only click this vote link after you complete previous vote!');
			return;
		}
		
		/** re-encapsulate the link arguments to one Vote.Link Object for easy using **/
		var clink = new Vote.Link(null, null, linknum, site, link, pid, timer);
		
		btn.innerHTML = Vote.CONS.VOTE_LABEL_VOTING;
		btn.disabled = true;
		btn.className = 'disable';
        
        window.processingLink = clink; // recored current processing vote link
		window.processingBtn = btn;
		
		window.processingWin = window.open(clink.link, '_blank', 'menubar=no, toolbar=no, location=no, resizable=yes,scrollbars=yes');
		
		if (window.processingWin == null) {
			alert(Vote.CONS.BLOCKED_MSG);
			Vote.postVoted(false);
			return;
		}
		
		window.processingStart = new Date().getTime();
		setTimeout(Vote.watchDog, 500);
	},
	
	/**
	 * The watch dog, used to monitor whether the opened vote link closed or not
	 */
	watchDog: function() {
		if (window.processingWin.closed) {
			if ((new Date().getTime() - window.processingStart) < window.processingLink.timer) { // player closed the window but not stay for enough time
			    Vote.postVoted(false);
			} else { // user stayed for enough time and closed the window
				Vote.postVoted(true);
			}
		} else {
			setTimeout(Vote.watchDog, 500);
		}
	},
	
	/**
	 * post voted processor, invoked when player done vote
	 * @param verified indicate whether current voting behaviour is passed checkVoted() or not
	 */
	postVoted: function(verified) {
		if (!verified) {
			alert(Vote.CONS.FAILURE_MSG);
			Vote.changeState(false);
		} else {
    		var l = window.processingLink;
    		
    		/** Ajax Use POST method **/
    		var req = Vote.Ajax.getTransport();
    		req.onreadystatechange = function() {
    			if (req.readyState == 4) {
    				if (req.status == 200) {    					
    					Vote.CONS.SUCCESS_MSG;
    					Vote.changeState(true);
    				} else {
    					alert(Vote.CONS.NONSUCCESS_MSG);
    					Vote.changeState(false);
    				}
    			}
    		};
    		var postBody = 'linknum=' + l.linknum + '&site=' + encodeURI(l.site) + '&link=' + encodeURIComponent(l.link) + '&pid=' + l.pid;
    		req.open('post', Vote.CONS.VOTE_URL, true);
    		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
    		req.send(postBody);
    		/** Ajax Use POST method end **/
		}
	},
	
	/**
	 * change the button state after posted no matter success or not
	 */
	changeState: function(success) {
		window.processingBtn.innerHTML = success ? Vote.CONS.VOTE_LABEL_DISABLE : Vote.CONS.VOTE_LABEL_AVAILABLE;
        window.processingBtn.disabled = success? true : false;
    	window.processingBtn.className = success ? 'disable' : '';
    	Vote.clear();
	},
	
	/**
	 * clear all state
	 */
	clear: function() {
        window.processingLink = null; // set to initial status
		window.processingBtn = null;
		window.processingWin = null;
		window.processingStart = null;		
	},
	
	/**
	 * Ajax utility, used to get the cross browser XMLHttpRequest object 
	 * can consider it as an abstract XMLHttpRequest builder factory
	 */
	Ajax: {
		getTransport: function() {
			if (window.XMLHttpRequest) {
				return new XMLHttpRequest();
			} else if (window.ActiveXObject) {
				var transport;
			    try {
			    	transport = new ActiveXObject('Msxml2.XMLHTTP');
			    } catch (e) {
			    	try {
			    	    transport = new ActiveXObject('Microsoft.XMLHTTP');
			    	} catch (ignore) {transport = null;}
			    }
			    return transport;
			} else {
				alert('Your browser not support XMLHttpRequest, please update your browser first');
				return null;
			}
		}
	}
};

