var page = null;

//define a mootools static class
var Utils = new Class({});
Utils.cutTextToDimension = function(text, dimension)
{
	if(text.length > dimension)
		return text.substr(0,dimension-3) + '...';
	else 
		return text;
};

Utils.createCopyObject = function(insertedIn,id,text,left,top,width,height)
{
	if(!$(insertedIn) || navigator.userAgent.match(/MSIE/))
		return;
	
	// create floating DIV above element
	var div = document.createElement('div');
	var style = div.style;
	style.position = 'absolute';
	style.left = '' + left + 'px';
	style.top = '' + top + 'px';
	style.width = '' + width + 'px';
	style.height = '' + height + 'px';
	style.zIndex = 99;
	
	var moviePath= 'copy2clipboard.swf';
	var movieId = 'ZeroClipboardMovie_' + id;
	
	// return HTML for movie
	var html = '';
	var flashvars = 'id=' + id +
		'&width=' + width +
		'&height=' + height;

	html += '<embed id="'+movieId+'" src="'+moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';

	div.innerHTML = html;
	
	$(insertedIn).adopt(div);

	
	setTimeout( function() {
		movie = document.getElementById(movieId);
		if(movie.setText != undefined)
			movie.setText(text);
	}, 1000 );
};

Utils.copyToClipboard = function(field)
{
	if (navigator.userAgent.match(/MSIE/)) 
	{
		var content = $(field);
		content.focus();
		content.select();
		range = content.createTextRange();
		range.execCommand("Copy");
   }
};

Utils.updateShowFirstDialog = function(state)
{
	var cookie_prefix = "show_first_list";
	
	if(Cookie.read(cookie_prefix) == null)
		Cookie.write(cookie_prefix, true);
	Cookie.write(cookie_prefix, state);
};

Utils.getShowFirst = function()
{
	var cookie_prefix = "show_first_list";
	var value = Cookie.read(cookie_prefix);
	
	if(value == null)
	{
		Utils.updateShowFirstDialog(true);
		return true;
	}
	
	return (value == 'true') ? true : false;
};

Utils.addView = function()
{
	var req = new Request({
		url: 'handlers/handler.list.php',
		method: 'post',
		data: { 'form_action' : 'add_view', 'list_id' : global_list_id },
		onSuccess: function() {}
	}).send();
};

Utils.vote = function(url_id, direction)
{
	if(direction == undefined || direction == null)
		direction = "plus";

	//Utils.post('list.php',{'url_id': data.id});
	var val = Cookie.read('url_' + url_id);
	if(val == null)
	{
		Cookie.write('url_' + url_id, 0);
		val = 0;
		//try to read it and if we can't it means that the cookies are disabled
		var test_val = Cookie.read('url_' + url_id);
		if(test_val == null)
		{
			alert("You have to enable cookies to vote");
			return;
		}
	}else
		val = parseInt(val); 

	if((val == 1 && direction == "plus") || (val == -1 && direction == "minus"))
	{
		showMessage('Only one vote is allowed for each url!', MessageType.ERROR);
		return;
	}
	
	var req = new Request({
		url: 'handlers/handler.list.php',
		method: 'post',
		async: false,
		data: { 'form_action' : 'vote_url', 'list_id' : global_list_id, 'url_id' : url_id, 'direction' : direction },
		onSuccess: function(args) {
			if(args.length == 0)
			{
				showMessage('Something went wrong!', MessageType.ERROR);
				return;
			}
			
			//update the global list object and the html
			var responseContent = "votable_list_box_" + url_id;
			var toolbarContent = "div_votes";
			for(var i=0;i<gListUrls.length;i++)
			{
				if(gListUrls[i].id == url_id)
				{
					gListUrls[i].votes = parseInt(args);
					if(responseContent && $(responseContent))
						$(responseContent).innerHTML = gListUrls[i].votes + '<br>votes';
					if(toolbarContent && $(toolbarContent))
						$(toolbarContent).innerHTML = gListUrls[i].votes + '<br>votes';
						
					break;
				}
			}
			
			//read the cookie
			var cookie_value = Cookie.read('url_' + url_id);
			cookie_value = parseInt(cookie_value);
			//write the cookie
			switch(direction)
			{
				case "plus":
					//read the cookie
					Cookie.write('url_' + url_id, cookie_value+1);
					break;
				case "minus":
					Cookie.write('url_' + url_id, cookie_value-1);
					break;
			}
		},
		onFailure: function(){
			showMessage('Something went wrong!', MessageType.ERROR);
		}
	}).send();
};

Utils.post = function(url, variables)
{
	var form=document.createElement("form");	
	form.setAttribute('action', url);
	form.setAttribute('method', 'POST');
	for ( var i in variables)
	{
		var newInput = document.createElement("input");
		newInput.setAttribute('type','hidden');
		newInput.setAttribute('name',i);
		newInput.setAttribute('value',variables[i]);
		form.appendChild(newInput);
	}
	document.body.appendChild(form);
	form.submit(); 
};

Utils.ListViews = {
	ToolbarView : 0,
	ThumbView 	: 1,
	VotingView	: 2
};



var IframePreloader = new Class({
	Implements: Events,
	
	initialize: function()
	{
		this.divIframes = $('div_iframes');
 		
		this.framesQueue = new Array();
 		this.inProgress = false;
 		this.searchTask = null;
 		this.current = null;
 		
 		this.isRunning = false;
 		
 		for(j=0;j<gListUrls.length;j++)
 			this.addIframeToDOM(j, gListUrls[j].show_in_frame,gListUrls[j].show_in_background, gListUrls[j].url);
	
 	},
 	
 	addIframeToDOM: function(index, bShowInFrame, bShowInBackground, url)
    {
    	//check if it is an item or not
    	var pattern_full = /^(http\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(?:\/\S*)?(?:[a-zA-Z0-9_])+\.(?:jpg|jpeg|gif|png))$/;
    	var matched_urls = url.match(pattern_full);
    	
    	bShowInFrame = (bShowInFrame == '') ? undefined : bShowInFrame;
    	
    	var urlEncode = function(url)
		{
			return encodeURIComponent(url).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
            replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '_');
		};
		
		var skip = true;
		if(matched_urls && matched_urls != null && matched_urls.length > 0 && url.indexOf('imgur') > -1)
		{
    		url = "item.php?type=imgur&url=" + urlEncode(url);
    		skip = false;
		}else if(bShowInFrame == false)
    		url = "item.php?type=iframe&url=" + urlEncode(url); 
		
		if(url.indexOf('crocodoc.com') > -1)
			url = "item.php?type=crocodoc&url=" + urlEncode(url);
		
		var newIframe = document.createElement('iframe');
		newIframe.id = 'iframe_' + index;
		newIframe.style.border = 'none';
		newIframe.width = '100%';
		newIframe.height = document.documentElement.clientHeight - 32; //try not to hardcode this resize
		newIframe.marginheight = '0';
		newIframe.marginwidth = '0';
		newIframe.noresize = 'noresize';
		newIframe.style.display = 'none';
		newIframe.frameBorder = 'no';
		
		this.divIframes.appendChild(newIframe);
		
		//get iframe status
		//here is the logic if the iframe is preloaded or not
		this.addIframe({
			'loaded' 				: false,
			//'skip' 					: (bShowInBackground == '0' || bShowInFrame == undefined) ? true : false,
			'skip'					: skip,
			'iframe_src'    		: url,
			'iframe_obj' 			: $(newIframe)
		});
		return newIframe;
    
    },
    
    goToUrl: function(index,currentUrl)
    {
		this.hideIframes();
		
		this.onChangeClear(currentUrl);
		
		var iframes = this.divIframes.getChildren();
		this.load(iframes[index].id);
		iframes[index].style.display = 'block';
    },
	
	start: function()
	{
		if(getInternetExplorerVersion() == 7)
			return;
		
		this.isRunning = true;
		//start a periodical that check every time if an iframe can be 
 		this.searchTask = this.search.periodical(1000);
 	},
 	block: function()
 	{
 		this.isRunning = false;
 	},
 	unblock: function()
 	{
 		this.isRunning = true;
 	},
	
	preloadIframe: function(candidate)
	{
		this.inProgress = true;
		//alert("loading: " + candidate.iframe_obj.id);
		//check the state of the url: if it is not active => force the onload event
		//async process => if the url is inactive the onload event will be forced
		this.urlIsActive(candidate.iframe_obj.id);
		
		candidate.iframe_obj.src = candidate.iframe_src;
		
		this.current = candidate;
	},
	
	addIframe: function(candidate)
	{
		//set extra properties to the candidate
		candidate.cleared 	= false;
		candidate.isActive  = false;
		
		this.framesQueue.push(candidate);
		
		var onload = function() 
		{
			var isCleared = candidate.cleared;
			if(isCleared == false && candidate.iframe_obj.src != "" && candidate.iframe_obj.src != undefined)
			{
				//alert(candidate.iframe_obj.id + " load is raised");
				page.preloader.OnLoadEventHandler({'id': candidate.iframe_obj.id, 'status' : 'ok'});
			}

			if(isCleared == true)
			{
				//alert(candidate.iframe_obj.id + " return to state");
				candidate.cleared = false;
			}
		};
		
		if((typeof candidate.iframe_obj.addEventListener) != 'undefined')
		{
			candidate.iframe_obj.addEventListener('load', onload ,false);
		}else if(candidate.iframe_obj.attachEvent)
		{
			candidate.iframe_obj.attachEvent('onload', onload);
    	}
		
	},

	//this is a task that is executed every second => it is used as a static method
	search: function()
	{
		var preloader = page.preloader;
		if(preloader.isRunning == false || preloader.inProgress == true)
			return;
		
		var candidate = null;
		preloader.framesQueue.each(function(frame,index)
		{
			if(candidate == null && frame.skip == false && frame.loaded == false)
				candidate = frame;
		});
		
		if(candidate != null)
			preloader.preloadIframe(candidate);
	},
	
	OnLoadEventHandler: function(args)
	{
		var iframe_id = args.id;
		var iframe_status = args.status;
		var candidate = this.getIframe(iframe_id);
		//alert(iframe_id + " is loaded");
		//if the candidate is loaded it means that already an event has been raised and the iframe is already loaded
		if(candidate.loaded == true)
			return;
		
		//if there is a timeout just reset the iframe and set it as loaded
		if(iframe_status == "ok")
		{
			//alert(iframe_id + "loaded");
			candidate.loaded = true;
			this.current = null;
		}
		
		//this unblocks the system if it is blocked
		this.unblock();
		this.inProgress = false;
	},
	
	getIframe: function(iframe_id)
	{
		//get the iframe 
		var candidate = null;
		this.framesQueue.each(function(frame,index)
		{
			if(candidate == null && frame.iframe_obj.id == iframe_id)
				candidate = frame;
		});
		
		return candidate;
	},
	
	load: function(iframe_id)
	{
		var candidate = this.getIframe(iframe_id);
		
		if(candidate == null || candidate.loaded == true)
			return;
		
		//stop the preloader
		if(this.inProgress == true)
		{
			this.clear(this.current.iframe_obj.id);
			this.inProgress = false;
		}
	
		this.block();
		this.preloadIframe(candidate);
	},
	
	onChangeClear: function(currentUrl)
	{
		var iframes = this.divIframes.getChildren();
		var iframe = this.getIframe(iframes[currentUrl].id);
		if(iframe != null && iframe.skip == true)
			this.clear(iframes[currentUrl].id, true);
	},
	clear: function(iframe_id)
	{
		for(var i in this.framesQueue)
		{
			if(this.framesQueue[i].iframe_obj && this.framesQueue[i].iframe_obj.id == iframe_id)
			{
				this.framesQueue[i].iframe_obj.src = ""; 
				this.framesQueue[i].loaded = false;
				this.framesQueue[i].cleared = true;
				
				break;
			}
		}
	},
	
	urlIsActive: function(iframe_id)
	{
		var candidate = this.getIframe(iframe_id);
		var host = candidate.iframe_src;
		var iframe_id = candidate.iframe_obj.id;
		
		var req = new Request({
			method: 'post',
			async: true,
			url: "iframe/ping.php",
			data: { 'url' : host },
			onComplete: function(response) { 
				if(response == "false")
				{
					page.preloader.OnLoadEventHandler({'id': iframe_id, 'status' : 'ok'});
				}
			}
		}).send();
	}, 
	
	hideIframes: function()
	{
		//hide all the iframes
		var iframes = this.divIframes.getChildren();
		iframes.each(function(el){
		    el.style.display = 'none';
		});
	}
});

var ToolbarView = new Class({
	
	initialize: function(){
		
		this.divToolbarView 	= $('div_toolbar_view');
		this.divMenuContent 	= $('div_menu_content');
		this.divUrlContainer 	= $('div_first_link');
		this.divVotes 			= $('div_votes');
		
		this.currentUrl = null;
    	
		this.pageUrlSize 	= 10;
		this.currentToolbarPage = null;
    	
		this.current = null;
		
		//add the events for the menu
		
		var elem = $('div_menu');
		var list = $('div_menu_links');
		list.style.display='none';
		//var myFx = new Fx.Slide(list).hide();
		elem.addEvents({
			'mouseenter' : function(){
				list.style.display='block';
				//myFx.cancel();
				//myFx.slideIn();
			},
			'mouseleave' : function(){
				list.style.display='none';
				//myFx.cancel();
				//myFx.slideOut();
			}
		});
		list.addEvents({
			'mouseenter' : function(){
				list.style.display='block';
				//myFx.cancel();
				//myFx.slideIn();
			},
			'mouseleave' : function(){
				list.style.display='none';
				//myFx.cancel();
				//myFx.slideOut();
			}
		});
		
		//check the clietn size ... if small resolution remove the text from toolbar
		var clientWidth = document.documentElement.clientWidth;
		if(clientWidth < 1180)
		{
			var buttons = $$("#div_buttons div");
			for(var i =0;i<buttons.length;i++)
			{
				buttons[i].innerHTML = "";
			}
		}
		
	}, 
	
	show: function(){
		this.refreshMenu(true);
		this.divToolbarView.show();
	},
	
	hide: function()
	{
		this.divToolbarView.hide();
	},
	
	prev: function()
	{
		var newPage = this.currentToolbarPage - 1;
		this.refreshMenu(false, newPage);
	},
	
	next: function()
	{
		var newPage = this.currentToolbarPage + 1;
		this.refreshMenu(false, newPage);
	},
	
	refreshMenu: function(bAutoGenerate,newPage)
	{
		//get the menu element
    	var menu = this.divMenuContent;
    	
    	//refresh only if the page is changed
    	var curr = (this.currentUrl == null) ? 0 : this.currentUrl;
    	
    	var currentPage = (bAutoGenerate) ? Math.floor(curr / this.pageUrlSize) : newPage;
    	if(currentPage != this.currentToolbarPage)
    	{
    		//clear the menu content;
	    	menu.innerHTML = "";
	    	for(var i= currentPage*this.pageUrlSize ;i<(currentPage+1)*this.pageUrlSize;i++)
	    	{
	    		if(gListUrls[i] == undefined)
	    			continue;
	    		
	    		var menuBgDiv = document.createElement('div');
		    	menuBgDiv.className = 'div_menu_item_bg';
		    		
		    	var menuItem = document.createElement('div');
		    	menuItem.className = ((i-(currentPage*this.pageUrlSize))%2 == 0) ? 'div_menu_item div_menu_item_odd' : 'div_menu_item div_menu_item_even';
		    		
		       	var aItem = document.createElement('a');
			    aItem.href = 'javascript:page.goToUrl(' + i + ');';
			    aItem.innerHTML = (gListUrls[i].url_title.length > 0 ) ?  Utils.cutTextToDimension(gListUrls[i].url_title,36) :  Utils.cutTextToDimension(gListUrls[i].url,36);
			    menuItem.appendChild(aItem);
			   	
			    menuBgDiv.appendChild(menuItem);
				menu.appendChild(menuBgDiv);
	    	}
	    	
	    	if(gListUrls.length >  this.pageUrlSize)
	    	{
		    	var menuBgDiv = document.createElement('div');
				menuBgDiv.className = 'div_menu_item_bg';
				
				var menuItem = document.createElement('div');
				menuItem.className = (this.pageUrlSize %2 == 0) ? 'div_menu_item div_menu_item_odd' : 'div_menu_item div_menu_item_even';
				
				if(currentPage != 0)
				{
					var previousLink 			= document.createElement('a');
					$(previousLink).setStyle('float',"left");
					previousLink.href 			= "javascript:page.renderPrev()";
					previousLink.innerHTML 		= "<< previous";
				
					menuItem.appendChild(previousLink);
				}
				if(currentPage != Math.floor(gListUrls.length/this.pageUrlSize))
				{
					var nextLink 			= document.createElement('a');
					$(nextLink).setStyle('float',"right");
					$(nextLink).setStyle('margin-right',"10px");
					nextLink.href 			= "javascript:page.renderNext()";
					nextLink.innerHTML 		= "next >>";
					menuItem.appendChild(nextLink);
				}
				
				menuBgDiv.appendChild(menuItem);
				menu.appendChild(menuBgDiv);
	    	}
			
	    	//save the page 
			this.currentToolbarPage = currentPage;
    	}
    	
    	//update the votes
    	if(this.divVotes != null)
    	{
    		var curr = (this.getCurrent() == null) ?  0 : this.getCurrent();
    		this.divVotes.innerHTML = gListUrls[curr].votes + "<br>votes";
    	}
	},
	refreshUrl: function()
	{
		this.divUrlContainer.innerHTML = (gListUrls[this.currentUrl].url_title.length > 0 ) ? Utils.cutTextToDimension(gListUrls[this.currentUrl].url_title,37) : Utils.cutTextToDimension(gListUrls[this.currentUrl].url,37);
	},
	
	showURL: function()
	{
		document.location = gListUrls[this.currentUrl].url;
	}, 
	
	getCurrent: function()
	{
		return this.currentUrl;
	},
	
	setCurrent: function(value)
	{
		this.currentUrl = value; 
		
		this.refreshMenu(true);
		this.refreshUrl();
	}
});

var VotingView = new Class({
	initialize: function(){
		
	this.divVotingView = $('div_voting_view');
		this.divUrlContainer = $('votable_list_urls');
		this.divPrev = $('votable_prev');
		this.divNext = $('votable_next');
		
		this.itemsPerPage = 10;
    	this.currentPage = -1;
    	
    	this.totalPages = Math.ceil(gListUrls.length/this.itemsPerPage);
    	
    	this.next();
    },
	
    show: function(){
		this.divVotingView.show();
	},
	
	hide: function(){
		this.divVotingView.hide();
	},
	
	next: function(){
		this.currentPage += 1;
		
		//clear the div
		this.divUrlContainer.innerHTML = "";
		
		var startIndex = this.currentPage*this.itemsPerPage;
		var endIndex = (this.currentPage+1)*this.itemsPerPage;
		
		this.insertUrls(startIndex, endIndex);
		
		this.refreshNavigation();
	},
	
	prev: function(){
		
		this.currentPage -= 1;
		
		//clear the div
		this.divUrlContainer.innerHTML = "";
		
		var startIndex = this.currentPage*this.itemsPerPage;
		var endIndex = (this.currentPage+1)*this.itemsPerPage;
		
		this.insertUrls(startIndex, endIndex);
		
		this.refreshNavigation();
	},
	
	insertUrls: function(startIndex,endIndex)
	{
		for(var i=startIndex;i<endIndex;i++)
    	{
    		if(gListUrls[i] == undefined)
    			continue;
    		var newRow = this.createDisplayRow(i,gListUrls[i]);
    		this.divUrlContainer.appendChild(newRow);
    	}
	},
	refreshNavigation: function()
	{
		if(this.totalPages == 1 || this.totalPages == 0)
		{
			this.divNext.hide();
			this.divPrev.hide();
			return;
		}
		if(this.currentPage == this.totalPages-1)
		{
			this.divNext.hide();
			this.divPrev.show();
			return;
		}
		if(this.currentPage == 0)
		{
			this.divNext.show();
			this.divPrev.hide();
			return;
		}
		this.divNext.show();
		this.divPrev.show();
	},

	createDisplayRow: function(index, data){
		var id = data.id;
		
		var rowContainer = document.createElement('div');
		rowContainer.id = 'voting_url_row_' + id;
		rowContainer.className = 'voting_url_row';
		
		var voteBox = document.createElement('div');
		//voteBox.id = ;
		voteBox.className = 'votable_list_box';
		
		var voteBoxCounter = document.createElement('div');
		voteBoxCounter.id = "votable_list_box_" + id;
		voteBoxCounter.innerHTML = (parseInt(data.votes) >= 0) ? data.votes + "<br/>votes" : "0<br/>votes";
		
		voteBox.appendChild(voteBoxCounter);
		
		var voteContainer = document.createElement('div');
		voteContainer.style.width = '55px';
		
		var voteDownBox = document.createElement('div');
		voteDownBox.className = 'votable_list_box_down';
		voteDownBox.innerHTML = '&nbsp;';
		
		var voteUpBox = document.createElement('div');
		voteUpBox.className = 'votable_list_box_up';
		voteUpBox.innerHTML = '&nbsp;';
		
		voteContainer.appendChild(voteDownBox);
		voteContainer.appendChild(voteUpBox);
		
		voteBox.appendChild(voteContainer);
		
		$(voteUpBox).addEvents({
			'click' : function(){
				Utils.vote(data.id, "plus");
			}
		});
		
		$(voteDownBox).addEvents({
			'click' : function(){
				Utils.vote(data.id, "minus");
			}
		});
		
		
		var rowImageContainer = document.createElement('div');
		rowImageContainer.id = 'voting_url_image_container_' + id;
		rowImageContainer.className = 'voting_url_image_container';
		
		var rowImage = document.createElement('img');
		rowImage.src =  global_thumbnail_small.replace('***url***', data.url);
		
		var imageAnchor = document.createElement('a');
		imageAnchor.href = 'javascript:page.goToUrl(' + index + ');';
		
		var detailsContainer = document.createElement('div');
		detailsContainer.id = 'voting_url_details_' + id;
		detailsContainer.className = 'voting_url_details';
		
		var titleAnchor = document.createElement('a');
		titleAnchor.href = 'javascript:page.goToUrl(' + index + ');';
		titleAnchor.innerHTML = (data.url_title.length > 0) ? data.url_title : data.url;
		titleAnchor.className = 'voting_url_title';
		
		var description = document.createElement('div');
		description.id = 'voting_url_description_' + id;
		description.className = 'voting_url_description';
		description.innerHTML = data.url_des;
		
		
		rowContainer.appendChild(voteBox);
		
		imageAnchor.appendChild(rowImage);
		rowImageContainer.appendChild(imageAnchor);
		
		rowContainer.appendChild(rowImageContainer);
		
		detailsContainer.appendChild(titleAnchor);
		detailsContainer.appendChild(description);
			
		rowContainer.appendChild(detailsContainer);
		
		return $(rowContainer);
	}
	
});

var ThumbView = new Class({
	initialize: function()
	{
	    this.divListView = $('div_list_view');
		this.contentWrapper = $('div_content_wrapper');
		
		this.framesPerPage = 0;
		this.currentPage = 1;
		this.frameSize = 'normal';
		
		//Number of loaded pages/iframes
		this.numLoadedFrames = 0;
		
		//set the content wrapper to fixed size => client width and than calculate the frames
		this.contentWrapper.setStyle('width', document.documentElement.clientWidth);
		
		this.framesPerPage = this.calculateFrames(this.frameSize);
		/*Try to have at least 6 frames per page, use small frames if needed.*/
		if (this.framesPerPage < 6)
		{
			this.frameSize = 'small';
			this.framesPerPage = this.calculateFrames(this.frameSize);
		}
		
		if (gListUrls.length % this.framesPerPage != 0) /*last page is half full*/
			this.numOfPages = Math.floor(gListUrls.length / this.framesPerPage) + 1;
		else /*last page exactly full*/
			this.numOfPages = Math.floor(gListUrls.length / this.framesPerPage);
		
		var thumbnailsContainer = $('div_page_placeholder');
		var marginLeft = 0;
		/*Create array of pages, each one is a Div element*/
		for(i=1; i<=this.numOfPages; i++)
		{
			var divPage = document.createElement('div');
			divPage.id = 'div_thumbs_container_page' + i;
			divPage.className = 'div_thumbs_container_page';
	
			/*Hide all pages except page 1*/
			if (i>1)
				divPage.style.display = 'none';
				
			/*Create thumbnail for this page*/
			var firstThumbForThisPage = (i-1) * this.framesPerPage;
			var lastThumbForThisPage = Math.min(i * this.framesPerPage, gListUrls.length);
			
			for(j=firstThumbForThisPage; j<lastThumbForThisPage; j++)
			{
				//Create thumbnail for URL
				var newUrlDiv = this.createUrlElement(gListUrls[j].url, gListUrls[j].url_title, j);
				divPage.appendChild(newUrlDiv);
			}
			thumbnailsContainer.appendChild(divPage);
			divPage.style.width = this.pageWidth + 'px';
			/*First time calc margin left for all pages.*/
			if (i==1)
				marginLeft = 0-(Math.floor(divPage.clientWidth / 2));
			divPage.style.marginLeft = marginLeft + 'px';
		
		}
		
		
		//this is for no script view
		if($('div_left_arrow') != null && $('div_right_arrow') != null)
		{
			$('div_left_arrow').setStyle('visibility','visible');
			$('div_right_arrow').setStyle('visibility','visible');
		}
		
		this.refreshNavigation();
	},
	
	show: function()
	{
		this.divListView.show();
	},
	
	hide: function()
	{
		this.divListView.hide();
	},
	
	next: function()
	{
		/*If last page - do nothing*/
		if (this.currentPage == this.numOfPages)
			return;
		/*Hide current page, show next page, increase counter*/
		$('div_thumbs_container_page' + this.currentPage).style.display = 'none';
		$('div_thumbs_container_page' + (this.currentPage + 1)).style.display = '';
		this.currentPage++;
		this.refreshNavigation();
	},
	
	prev: function()
	{
		/*If last page - do nothing*/
		if (this.currentPage == 1)
			return;
		
		/*Hide current page, show next page, increase counter*/
		$('div_thumbs_container_page' + this.currentPage).style.display = 'none';
		$('div_thumbs_container_page' + (this.currentPage - 1)).style.display = '';
		this.currentPage--;
		this.refreshNavigation();
	},
	
	calculateFrames: function(size)
	{
		
		if (size == 'normal')
		{
			var thumbnailHeight = 229;
			var thumbnailWidth = 270;
		}
		else if (size == 'small')
		{
			var thumbnailHeight = 187;
			var thumbnailWidth = 220;
		}

		var headerHeight = $('div_header').clientHeight;
		var footerHeight = $('div_footer').clientHeight;
		//var leftBarWidth = $('div_left_arrow').clientWidth;
		//var rightBarWidth = $('div_right_arrow').clientWidth;
		var leftBarWidth = $('div_left_arrow').offsetWidth;
		var rightBarWidth = $('div_right_arrow').offsetWidth;
		
		var placeholderHeight = document.documentElement.clientHeight - headerHeight - footerHeight;
		var placeholderWidth = document.documentElement.clientWidth - leftBarWidth - rightBarWidth;
		$('div_page_placeholder').style.height = placeholderHeight + 'px';
		$('div_page_placeholder').style.width = placeholderWidth + 'px';
		
		$('div_left_arrow').style.height = placeholderHeight + 'px';
		$('div_right_arrow').style.height = placeholderHeight + 'px';
		
		var numberOfFramesInACol = Math.floor(placeholderHeight / thumbnailHeight);
		var numberOfFramesInARow = Math.floor(placeholderWidth / thumbnailWidth);

		this.pageWidth = thumbnailWidth * numberOfFramesInARow;

		return numberOfFramesInACol * numberOfFramesInARow;
	},
	
	refreshNavigation: function()
	{
		//If last page - hide next arrow
		if (this.currentPage == this.numOfPages)
			$('div_right_arrow_image').style.display = 'none';
		else
			$('div_right_arrow_image').style.display = 'block';
		
		//If last page - hide next arrow
		if (this.currentPage == 1)
			$('div_left_arrow_image').style.display = 'none';
		else
			$('div_left_arrow_image').style.display = 'block';
	},
	
	// Create one thumbnail element
	createUrlElement: function(url, anchor, index, type)
	{
		/*Create thumbnail div*/
		var newDiv = document.createElement('div');
		if (this.frameSize == 'normal')
			newDiv.className = 'div_thumb_frame';
		else
			newDiv.className = 'div_thumb_frame_small';
		
		$(newDiv).addEvent('mouseover',function(event){
			 event.stop();
			 $(this).className = $(this).className + '_blue';
		});
		$(newDiv).addEvent('mouseout',function(event){
			 event.stop();
			 $(this).className = $(this).className.replace("_blue","");
		});
		
		/*Create internal img element and anchor, append inside div*/
		var newImg = document.createElement('img');
		newImg.src = global_thumbnail_small.replace('***url***', url);
		//newImg.src = 'http://images.pageglimpse.com/v1/thumbnails?url=' + url + 
		//'&size=medium&devkey=3397f3b35c6ee99e3d326120d25d9b99';
		/*newImg.src = 'http://images.websnapr.com/?size=size&key=9Vfd22fZwh99&url=' + url;*/
		if (this.frameSize == 'normal')
			newImg.className = 'img_thumb';
		else
			newImg.className = 'img_thumb_small';
		
		var imageAnchorElement = document.createElement('a');
		imageAnchorElement.href = (type != 'new_tab') ? 'javascript:page.goToUrl(' + index + ');' : url; //url;
		imageAnchorElement.target = (type != 'new_tab') ? '_self' : '_blank';
		imageAnchorElement.appendChild(newImg);
		newDiv.appendChild(imageAnchorElement);
		
		/*Create anchor*/
		var lineBreak = document.createElement('br');
		var anchorElement = document.createElement('a');
		anchorElement.href = (type != 'new_tab') ? 'javascript:page.goToUrl(' + index + ');' : url; //url; 
		anchorElement.target = (type != 'new_tab') ? '_self' : '_blank';
		anchorElement.innerHTML = anchor;
		anchorElement.className = 'anchor_thumb';
		newDiv.appendChild(lineBreak);
		newDiv.appendChild(anchorElement);
		
		return newDiv;
	}


});


var ListPage = new Class({
	initialize: function(type)
	{
		this.prerenderComponent = null;
		this.renderComponent = new ToolbarView();
		
		switch(type)
		{
			case Utils.ListViews.ThumbView:
				this.prerenderComponent = new ThumbView();
			break;
			case Utils.ListViews.VotingView:
				this.prerenderComponent = new VotingView();
			break;
		}
		
		this.preloader = new IframePreloader();
		this.preloader.start();
		
		var hash_string = window.location.hash;
		var hash = hash_string.substring(1,hash_string.length);
		var is_numeric = (hash - 0) == hash && hash.length > 0;

		if(is_numeric && hash > 0 && hash <= gListUrls.length)
			this.goToUrl(hash-1);
		
	},
	
	prerenderNext: function()
	{
		this.prerenderComponent.next();
	},
	
	prerenderPrev: function()
	{
		this.prerenderComponent.prev();
	}, 
	
	renderNext: function()
	{
		this.renderComponent.next();
	},
	
	renderPrev: function()
	{
		this.renderComponent.prev();
	},
	
	loadRender: function()
	{
		//this is just a workaround 
		//TODO: get rid of it
		$(document.body).setStyle('background-color','#ffffff');

		this.prerenderComponent.hide();
		this.renderComponent.show();
	},
	
	loadPrerender: function()
	{
		//this is just a workaround 
		//TODO: get rid of it
		$(document.body).setStyle('background-color','#75BDEF');
		
		this.prerenderComponent.show();
		this.renderComponent.hide();
		this.preloader.hideIframes();
		
		var curr = this.renderComponent.getCurrent();
		this.preloader.onChangeClear(curr);
	},
	
	goToUrl: function(index)
	{
		this.loadRender();
		this.renderComponent.setCurrent(index);
		
		this.preloader.goToUrl(index,this.renderComponent.getCurrent());
	},
	
	nextUrl: function()
	{
		var curr = this.renderComponent.getCurrent()+1;
		if(curr == gListUrls.length)
			this.loadPrerender();
		else
			this.goToUrl(curr);
	},
	prevUrl: function()
	{
		var curr = this.renderComponent.getCurrent()-1;
		if(curr == -1)
			this.loadPrerender();
		else
			this.goToUrl(curr);
	}, 
	
	addUrl: function(title_id, url_id, title, url, description)
	{
	 	var regularExp = /^[ a-zA-Z0-9_-]*$/;
	    var error = null;
		
	    //validate them
		if(!title.test(regularExp))
		{
			error += "Url Title invalid<br>";
			this.highlightInput(title_id,true);
		}
		
		if(url.length == 0 || url == "http://")
		{
			error += "Url Title invalid";
			this.highlightInput(url_id, true);
		}
		
		if(error == null)
		{
			var req = new Request({
				url: 'handlers/handler.list.php',
				method: 'post',
				async: false,
				data: {
					'form_action' 	: 'add_url',
					'list_id' 		: global_list_id, 
					'url_title' 	: title,
					'url'			: url,
					'description' 	: description
				},
				onSuccess: function(args) {
					
					//cloase the current dialog
					dialog.close();
				
					if(args == "1")
						showMessage('The Url was added. Click ok to refresh the page',MessageType.SUCCESS, function() { window.location = global_list_url; });
					else
						showMessage('Something went wrong', MessageType.ERROR);
				},
				onFailure: function(){
					//cloase the current dialog
					dialog.close();
					//show on success message
					showMessage('Something wen wrong',MessageType.ERROR);
				}

			}).send();

		}
	},
	
	highlightInput:function(divInputId,state)
	{
		var div_input_childs = $$('#' + divInputId + " div");
		if(div_input_childs)
		{
			for(var key in div_input_childs)
			{
				var div_child = div_input_childs[key];
				//get base class name
				var baseClass = this.getInputBaseClassName(div_child.className); 
				div_child.className = (!state) ? baseClass : baseClass + '_red';
			}
		}
	},
	
	getInputBaseClassName: function(className)
	{
		if(!className || className.indexOf("_red") == -1)
			return className;
		
		return className.substr(0,className.indexOf("_red"));
	}, 
	
	vote: function(direction)
	{
		var curr = this.renderComponent.getCurrent();
		Utils.vote(gListUrls[curr].id, direction);
	},
	
	openBunch: function()
	{
		if(confirm("Are you sure you want to open all links?"))
		{
			for(var index=0;index<gListUrls.length;index++)
			{
				open(gListUrls[index].url);
			}
		}
	}
	
});


window.addEvent('domready', function() {
	
	if(global_page_restricted)
		return;
	
	if(global_voting_list)
		page = new ListPage(Utils.ListViews.VotingView);
	else
		page = new ListPage(Utils.ListViews.ThumbView);
	
	if(global_is_first == true && Utils.getShowFirst())
		showDialog('dialog_list');
	
	Utils.createCopyObject('dialog_list_address_div',1,$('dialog_list_address').value,237,118,18,18);
	Utils.createCopyObject('dialog_list_edit_div',2,$('dialog_list_edit').value,237,203,18,18);
	Utils.createCopyObject('dialog_list_short_div',3,$('dialog_list_short').value,237,272,18,18);
	
	Utils.addView();
	
});

function getInternetExplorerVersion(){
	var rv = -1; // Return value assumes failure.
	if (navigator.appName == 'Microsoft Internet Explorer')
	{
		var ua = navigator.userAgent;
		var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
		if (re.exec(ua) != null)
			rv = parseFloat( RegExp.$1 );
	}
	return rv;
}

