var overrideSWF;
var magazineId;


var fullInteractive = {
	
	swfId       : "revista",
	
	SWFRef      : null,
	
	locationObj : parseUri(window.location.href),
	
	
	initSWF : function()
	{
		var flashvars  = {
			uri_protocol      : this.locationObj.protocol,
			uri_domain        : this.locationObj.domain,
			uri_port          : this.locationObj.port,
			uri_directoryPath : this.locationObj.directoryPath,
			uri_fileName      : this.locationObj.fileName,
			fullDynamicsId    : (magazineId !== undefined)  ? magazineId  : 1
		};
		
		var params        = {};
		var attributes    = {};
		var basePath      = '/assets/images/full/';
		var swfPath       = (overrideSWF !== undefined) ? overrideSWF : (basePath + 'fullinteractive.swf');
		
		params.scale = "exactfit";
		params.wmode = (
				(BrowserDetect.browser == 'Explorer') ||
				((BrowserDetect.browser == 'Firefox') && (BrowserDetect.OS == 'Windows'))
				) ? "transparent" : "window";
		params.bgcolor = "#eeeeee";
		params.allowfullscreen = "true";
		params.allowscriptaccess = "sameDomain";
		
		attributes.id = this.swfId;
		
		swfobject.embedSWF(swfPath, "main", "100%", "100%", "10.0.0", basePath + "expressInstall.swf", flashvars, params, attributes);
		
		this.SWFRef = this.getSWFRef();
		
		$("body").addClass("jsfied");
	},
	
	
	getSWFRef : function()
	{
		if (navigator.appName.indexOf("Microsoft") != -1)
		{
			return window[this.swfId];
		}
		else
		{
			return document[this.swfId];
		}	
	},
	
	
	
	analytics : {

		url          : '/analytics/',
		userId       : null,
		trackingCode : null,
		ready        : false,


		init : function(trackingCode, systemInfo)
		{
			this.trackingCode = trackingCode;
			
			var postData = {
				'trackingCode'      : this.trackingCode,
				'browser_name'      : BrowserDetect.browser,
				'browser_version'   : BrowserDetect.version,
				'OS_name'           : BrowserDetect.OS,
				'OS_version'        : systemInfo.os,
				'flash_version'     : String(systemInfo.flashVersion).split(' ')[1],
				'language'          : systemInfo.language,
				'screenResolutionX' : systemInfo.screenResolutionX,
				'screenResolutionY' : systemInfo.screenResolutionY,
				'url'               : window.location.href,
				'referer'           : (document.referrer) ? document.referrer : null
			};
			
			if( (this.trackingCode != null) && (this.trackingCode != 'null') )
			{
				this.ready = true;
			}
			
			
			if(this.ready)
			{
				var _this = this;
			
				$.post( this.url, postData, function(data)
				{
					if( data == -1 )
					{
						_this.ready = false;
					}
					else
					{
						_this.userId = data;
					}
				});
			}
		},
		
		
		notifyAction : function(actionId, actionParams)
		{
			var actionParamsData = null;
			
			switch(actionId)
			{
				case 0:
					// page turn
					actionParamsData = [
						actionParams.page,      // n. página
						actionParams.time       // tiempo
					];
					break;
				case 1:
					//
					actionParamsData = [];
					break;
				default:
					break;
			}
			
			
			if(actionParamsData != null)
			{
				var postData = {
					'userId'         : this.userId,
					'actionId'       : actionId,
					'actionParams[]' : actionParamsData
				};
				
				var _this = this;
				
				if(this.ready)
				{
					$.post( this.url, postData, function(data)
					{
						if( data == -1 )
						{
							_this.ready = false;
						}
					});
					
					pageTracker._trackEvent(
						'FullMagazine',
						'PageView',
							'url:' + window.location.href +
							'-trackingCode: ' + this.trackingCode + 
							'-actionId: ' + actionId +
							'-userId: ' + this.userId +
							'-page: ' + actionParams.page +
							'-time: ' + actionParams.time
					);
				}
			}
		},
		
		trackAd : function(advertisementId)
		{
			pageTracker._trackEvent(
				'FullMagazine',
				'AdClicked',
				'advertisementId: ' + advertisementId
			);
		}
	},
	
	
	windowManager : {

		resizeWin : function()
		{
			var w = screen.availWidth;
			var h = screen.availHeight - 50;

			var newW = (w <= 1200) ? w : 1200;
			var newH = (h <= 1000) ? h : 1000;

			window.resizeTo(newW, newH);
		},
		
		
		repositionWin : function()
		{
			var xPos    = 0;
			var yPos    = 0;
			var wWidth  = 0;
			var wHeight = 0;

			if (window.innerWidth)
			{
			  wWidth = window.innerWidth;
			  wHeight = window.innerHeight;
			}
			else if (document.documentElement && document.documentElement.clientWidth)
			{
			  wWidth = document.documentElement.clientWidth;
			  wHeight = document.documentElement.clientHeight;
			}
			else if (document.body)
			{
			  wWidth = document.body.clientWidth;
			  wHeight = document.body.clientHeight;
			}
			if( (wWidth != 0) || (wHeight != 0) )
			{
				window.moveTo( ( (screen.availWidth - wWidth) / 2 ), ( (screen.availHeight - wHeight) /2 ) );
			}
		}
	},
	
	
	utils : {
		
		showAdvertisementsForm : function(params)
		{
			var strUrl    = "/setAdvertisement.php";
			var strParams = "magazineId=" + params.magazineId + "&sectionId=" + params.sectionId + "&";
			
			tb_show("", strUrl + "?" + strParams + "keepThis=true&TB_iframe=true&height=450&width=600", false);
		},
		
		showGalleryForm : function(params)
		{
			var strUrl    = "/setImage.php";
			var strParams = "magazineId=" + params.magazineId + "&sectionId=" + params.sectionId + "&";
			
			tb_show("", strUrl + "?" + strParams + "keepThis=true&TB_iframe=true&height=450&width=600", false);
		},
		
		showImg : function(params)
		{
			var title = (params.user == "") ? params.title : (params.user + ": " + params.title);
			tb_show(title, params.image, false);
		},
		
		showCommentsForm : function(params)
		{
			var strUrl    = "/setComment.php";
			var strParams = "magazineId=" + params.magazineId + "&sectionId=" + params.sectionId + "&";
			
			tb_show("", strUrl + "?" + strParams + "keepThis=true&TB_iframe=true&height=450&width=600", false);
		},
		
		showPrizeDrawForm : function(params)
		{
			var strUrl    = "/checkWinner.php";
			var strParams = "magazineId=" + params.magazineId + "&sectionId=" + params.sectionId + "&";
			
			tb_show("", strUrl + "?" + strParams + "keepThis=true&TB_iframe=true&height=450&width=600", false);
		}
	},
	
	
	maps : {
		
		loadMap : function(params)
		{
			// remove previous maps and reset the arrays
			$("#mapContainer").remove();
			
			// create the map container
			$("body").append('<div id="mapContainer"></div>');
			$("#mapContainer").append('<div id="mapHolder" style="width:100%; height:100%;"></div>');
			
			// create the thickbox
			tb_show("Mapa", "#TB_inline?height=650&width=800&inlineId=mapContainer&modal=false", false);
			
			if(google.maps === undefined)
			{
				// maps libraries not loaded yet
				setTimeout(function(){ fullInteractive.maps.showMap(params); }, 2000);
			}
			else
			{
				fullInteractive.maps.showMap(params);
			}
			
			
			
		},
		
		showMap : function(params)
		{
			// init the map
			var map = new google.maps.Map(
				document.getElementById("mapHolder"),
				{
					zoom      : params.zoom,
					center    : new google.maps.LatLng(params.latitude, params.longitude),
					mapTypeId : google.maps.MapTypeId[params.mapType]
				}
			);
			
			// setup any infoWindows
			for(var i = 0; i < params.markers.length; i++)
			{
				if(params.markers[i].infoWindow == null) continue;
				
				var infowindow = new google.maps.InfoWindow({
				    content : params.markers[i].infoWindow
				});

				var marker = new google.maps.Marker({
				    position : new google.maps.LatLng(params.markers[i].latitude, params.markers[i].longitude),
				    map      : map,
				    title    : params.markers[i].title
				});

				google.maps.event.addListener(marker, 'click', function() {
				  infowindow.open(map,marker);
				});
			}
			
		}
	}
	
};


$(document).ready(function()
{
	fullInteractive.windowManager.resizeWin();
	fullInteractive.windowManager.repositionWin();
	fullInteractive.initSWF();
});


$(window).unload(function()
{
	if( fullInteractive.SWFRef )
	{
		fullInteractive.SWFRef.notifyLastPageTime();
	}
});




/*
	Browser detect, by Peter-Paul Koch
	http://www.quirksmode.org/js/detect.html
*/
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{	// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();



/* parseUri JS v0.1.1, by Steven Levithan <http://stevenlevithan.com>
Splits any well-formed URI into the following parts (all are optional):
----------------------
- source (since the exec method returns the entire match as key 0, we might as well use it)
- protocol (i.e., scheme)
- authority (includes both the domain and port)
  - domain (i.e., host; can be an IP address)
  - port
- path (includes both the directory path and filename)
  - directoryPath (supports directories with periods, and without a trailing backslash)
  - fileName
- query (does not include the leading question mark)
- anchor (i.e., fragment) */
function parseUri(sourceUri){
	var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"],
		uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri),
		uri = {};
	
	for(var i = 0; i < 10; i++){
		uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
	}
	
	/* Always end directoryPath with a trailing backslash if a path was present in the source URI
	Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key */
	if(uri.directoryPath.length > 0){
		uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
	}
	
	return uri;
}
