//
//Flipbook Class for STATS
//
var _gaq = _gaq || [];
function Flipbook(id, type){
	//will not send requests to db if time between flips are less than this amount
	this.secondsPerFlip = 1.5; 
	
	this.id = id;
	this.type = type;
	this.readId = null;	
	
	this.pages = [];
	this.articles = [];
	this.openPages = [];
	
	this.page = null;
	
	this.lastFlipTime = null;
	
	this.open = function(){
		$j.ajax({
			flipbookInstance: this,
			type: "POST",
			url: g_webroot + "read/ajax_flipbookOpen/"+this.id+"/"+this.type,
			success: function(readId){
				this.flipbookInstance.readId = readId;
			}
		});
	}
	
	this.close = function(){
		this.closeOpenPages();
		
		$j.ajax({
			type: "POST",
			async: false,
			url: g_webroot + "read/ajax_flipbookClose/"+this.readId+"/"+this.type
		});
	}
	
	this.isFastFlipping = function(){
		var currFlipTime = new Date().getTime();
		var ret = false;
		
		if( this.lastFlipTime == null ){
			this.lastFlipTime = currFlipTime;
		} else {
			if( Math.round( (currFlipTime - this.lastFlipTime)/1000 ) < this.secondsPerFlip ){
				ret = true;		
			}
		}
		this.lastFlipTime = currFlipTime;
		
		return ret;
	}
	
	this.flip = function(pageFl, zoom){
		this.page = this.getPage(pageFl, zoom);

		if( !this.page.isOpen ){
			this.closeOpenPages();
			
			//opening new pages
			if(g_spread){
				if( this.page.isOdd() ){ //1,3,5,7
					currRightPage = this.getPage(this.page.pageFl+1);
					this.openPage( currRightPage );
					
				} else if( !this.page.isOdd() && !this.page.isCover() ){ //2,4,6
					currLeftPage = this.getPage(this.page.pageFl-1);
					this.openPage( currLeftPage );
				}
			}
			this.openPage(this.page);
		}
	}
	
	this.zoomPoint = function(pageFl, x, y){
		this.page = this.getPage(pageFl);
		this.page.zoomPoint(x, y);
	}
	
	this.closeOpenPages = function(){
		if( this.openPages.length > 0 ){
			for(pageFl in this.openPages ){
				this.closePage(this.openPages[pageFl]);
			}	
		}
	}
	
	this.getPage = function(pageFl, zoom){		
		if( typeof this.pages[pageFl] == "undefined" ){
			this.pages[ pageFl ] = new Page(pageFl, zoom, this.type, this.id, this.readId);
		} else if( zoom != null ){
			this.pages[ pageFl ].zoom = zoom;
		}
		return this.pages[ pageFl ];
	}
		
	this.getCover = function(){
		return this.getPage(0);
	}
	
	this.openPage = function(page){
		page.open() 
		if( page.isOpen ){
			this.openPages[ page.pageFl ] = page;	
		}
	}
	
	this.closePage = function(page){
		page.close();
		delete this.openPages[ page.pageFl ];
	}	
}

//
//Page class
//
function Page(pageFl, zoom, type, typeId, typeReadId){
	//page id
	this.id = null;
	this.pageFl = pageFl;
	//page read id
	this.readId = null;
	//issue
	this.type = type;
	//issue_id
	this.typeId = typeId;
	//issue_reading_id
	this.typeReadId = typeReadId;
	this.zoom = zoom;
	this.isOpen = false;

	this.open = function(){
		if( !this.isOpen ){
			this.isOpen = true;

			// Execute Google Analytics
			ga_execute(pageFl);			
			
			$j.ajax({
				pageInstance: this,
				type: "POST",
				url: g_webroot + "read/ajax_pageOpen/"+this.id+"/"+this.pageFl+"/"+this.typeId+"/"+this.typeReadId+"/"+this.type,
				success: function(data){
					if( empty.test(data) ){
						return;
					}
					
					data = JSON.parse(data);
					
					if( empty.test(data.readId) ){
						this.pageInstance.isOpen = false;
					} else {
						this.pageInstance.readId = data.readId;	
						this.pageInstance.id = data.id;	
					}					
				}
			});	
		}
	}
	
	this.close = function(){
		if( this.isOpen && this.readId ){
			this.isOpen = false;
			$j.ajax({
				type: "POST",
				url: g_webroot + "read/ajax_pageClose/"+this.readId
			});
		}
	}
	
	this.zoomPoint = function(x,y){
		$j.ajax({
			type: "POST",
			url: g_webroot + "read/ajax_pageZoom/"+this.id+"/"+this.typeReadId+"/"+x+"/"+y
		});
	}
	
	this.isCover = function(){
		return (this.pageFl == 0)
	}
	
	this.isAfterCover = function(){
		return (this.pageFl == 1);
	}
	
	this.isOdd = function(){
		return !(this.pageFl%2 == 0);
	}
	
	this.compareTo = function(page){
		return (this.page.pageFl == page.pageFl);
	}
}

var g_flipbook = new Flipbook(g_id, g_type);
g_flipbook.open();

function close_flipbook(callCloseHandlers){
	if( callCloseHandlers == null ) callCloseHandlers = true;
	
	g_flipbook.close();
	
	//if this is a popup, close it, else return to mygazines.com
	//since we call this function onunload, it means the user has closed the 
	//window manually if set to false, we don't have to call these close handling
	//functions.
	
	// should always close the window
	
	if( callCloseHandlers ){
		//if(window.opener){
			window.close();
		//} else {
		//	document.location.href = g_webroot;
		//}
	}
}

var g_lastInterval = null;
function turn_page(page, zoom){
	if( zoom === null ) zoom = 1;

	//since setTimeout works in the background, if we quickly flip through pages
	//the setTimeout gets set in the background and all of them gets executed. this
	//clears last interval so they don't get executed. only when users sit for 3 seconds
	//on the page it will start to record
	if( g_lastInterval != null ){
		clearTimeout(g_lastInterval);
	}
	
	//to prevent users from bombarding our db we put this measure in
	//this will start sending requests to db after 3 seconds, this will make sure only pages that
	//users inted to read gets marked
	g_lastInterval = setTimeout(function(){ g_flipbook.flip(page, zoom); }, g_flipbook.secondsPerFlip * 1000);
	
	//if in preview mode, only allow user to flip a couple pages before being prompted to login in
	if(g_showLogin){
		
		//if(g_previewCount>3){
		if(page==(g_totalPreviewPages-1)){
		
			loadAuthentication();
		}
		
		

	}
	if(g_loading){closeLoader();}
	
	//if clipping widget enabled but still showing welcome text, show clippings
	if(g_pageViewCount>0 && typeof refreshSideBarClippings == 'function' && g_clippingsShowing==0) {
		refreshSideBarClippings();
	}
	
	g_pageViewCount++;
}

function zoom_in(page_num, x, y){
	g_flipbook.zoomPoint(page_num, x, y);
}

/* OTHER SHARED FUNCTIONALITY */
var g_authenticated = false;
function authenticate(login_action, login_fail_message){
	
	if( empty.test($j("#username").val()) ){
		$j("#username").focus();
		return false;
	}
	
	$j("#login").val("please wait...").attr("disabled", "disabled");
	$j.ajax({
		
		type: "POST",
		data: "data="+JSON.stringify({"title_id":g_titleId, "username":encodeURIComponent($j("#username").val()), "password":encodeURIComponent($j("#password").val())}),
		url: g_webroot + login_action,
		success: function(data){
			if( data == 1 || data=="A" ){
				g_authenticationed = true;
				$j("#login_form_submit").html("<br/><br/>Success! Please wait");
				$j("#login_form_submit").submit();
				
			} else {
				
				var msg = "Authentication failed. " + login_fail_message;
				if(data=="I")
					msg = "Sorry, your subscription has expired. Please contact us to renew.";
				else if(data=="V")
					msg = "Sorry, you will need to first verify your email address before gaining access to this publicaton. If you have not received an email verification request, please contact us.";
				else if(data=="Y")
					msg = "Sorry, we have yet to receive payment for your subscription. Please wait for confirmation that we've received payment or contact us for help.";
				else if(data=="IP_LIMIT_DENIED")
					msg = "Sorry, you have exceeded the limit of devices that can access your account today.";
				alert(msg);
				
				$j("#username").focus();
				$j("#login").val("submit").attr("disabled", "");
			
			}
		}
	});
	
	return g_authenticated;
	
}

function forgotCredentials(){
	
	if( empty.test($j("#forgot_creds_email").val()) ){
		$j("#forgot_creds_email").focus();
		return false;
	}
	
	$j("#forgot_creds_send").val("please wait...").attr("disabled", "disabled");
	$j.ajax({
		
		type: "POST",
		data: "data="+JSON.stringify({"title_id":g_titleId, "title_name":encodeURIComponent(g_titleName), "email":encodeURIComponent( $j("#forgot_creds_email").val() ) }),
		url: g_webroot + "subscribers/ajax_forgot_credentials/",
		success: function(data){
			if( data == 1 ){
				alert("Thank you. Please check your email for your credentials and then try logging in again.");
				$j('.forgot_creds_toggle').slideToggle();
			} else {
				if(data == 0)
					var msg = "Sorry, your email was not recognized. Please try again.";
				else
					var msg = data;
				alert(msg);
				
				$j("#forgot_creds_email").focus();
			}
			$j("#forgot_creds_send").val("send").attr("disabled", "");
		}
	});
	return false;
}

//Execute Google Analytics on Click/Load
function ga_execute(page) {
	//url = g_webroot + "read/issue/" + g_id + "/" + page;
	if(page != -1) {
		url = "/issue/" + g_id + "/" + page;
			
	//alert(url);	
	
		// Execute GA Tracker
		if(g_gaCodes && g_gaCodes.length > 0) {
			for(i=0;i<g_gaCodes.length;i++){
				_gaq.push(['_setAccount', g_gaCodes[i]],
						['_setDomainName', 'none'],
				  		['_setAllowLinker', true],
						['_trackPageview', url]
					);		
			}
		}
	}
}
