$('img[src="http://content.aimatch.com/default.gif"]').hide();

go = false;

Main = function() {
	this.init_DOM();
}

Main.prototype = {
	init_DOM: function() {
		this.base_url				= '/mobile';
		this.jSearchBar 			= $('#search_bar');
		this.jSearchBarSwitcher 	= $('.search-bar-switcher');
		this.jLoadMore				= $('.load-more button');
		this.jNoMoreToLoad			= $('.no-more-to-load');
		this.jLoadMoreRef			= $('.load-more-ref');

		this.jTrailersListLink		= ('.trailers-list-link');
		this.jTrailerList			= ('.trailer-link');

		this.jVoteLink				= ('.vote-link');

		this.jMainMenu     			= $('#mainmenu');			
		this.jMainMenuSwitcher		= $('#mainmenu-switcher');

		this.jFindLocation			= $('#find-location');
		this.jFindLocationSwitcher  = $('.find-location-switcher');
		this.jFindCinemaLocationSwitcher = $('.cinemas-find-location-switcher');
		this.jMovieLocationSwitcher = $('.movie-find-location-switcher');
		
		this.serach_bar_state		= false;
		this.mainmenu_state			= false;
		this.findlocation_state		= false;
		this.voting_state 			= false;
		this.loading_content        = false;

		this.btn_loading_html 		= 'Loading More...';
		this.btn_html 				= 'Load More';

		this.cssTransitions 		= function(){ return "WebKitTransitionEvent" in window };
	
		this.uagent 				= navigator.userAgent.toLowerCase();
		this.uplatform 				= navigator.platform.toLowerCase();
		this.href 					= window.location.href;
		this.hash 					= window.location.hash.substring(1);
		
		this.tabs 					= $('.tab');
		this.tabs_active 			= $('.tabs.active');
		this.tabs_switcher 			= $('.tabs-menu a');

		this.location_city			= (function(){
			if( window.location.hash.substring(1).match('city') ){
				var arr = window.location.hash.substring(1).split('city:');
				if( arr[1].match(';') ){
					var dif = arr[1].split(';');
					return dif[0];
				}
				else return arr[1];
			}
		})();

		this.tab			= (function(){
			if( window.location.hash.substring(1).match('tab') ){
				var arr = window.location.hash.substring(1).split('tab:');
				if( arr[1].match(';') ){
					var dif = arr[1].split(';');
					return dif[0];
				}
				else {
					return arr[1];	
				} 
			}
		})();


		this.back					= $('.back');
		
		this.jSearchByGenre			= $('#search-by-genre');
		this.jMovieVote			    = $('.movie-vote');
		this.jAddCinema			    = $('.add-cinema');
		
		this.jArticle				= $('article');
		this.jArticleVideoPlayer	= $('article object');
		this.jArticleIframe			= $('article iframe');
		
		this.jVoteReply				= $('#vote-reply');
		this.jVoteResult			= $('#vote-result');
		this.jVoteLoader			= $('#vote-loader');
		
		this.jMovieVoteLine			= $('.move-vote-line');
		
		this.jFindMe				= $('.find-me');
		
		this.jSwitchCityCinema		= $('#switch_city_cinema');
		this.jSwitchCityCinemaNearest	= $('#switch_city_nearest');
		this.jSwitchCityCommon		= $('.switch_city');
		
		this.init();
	},

	init: function() {

		this.setSearchBar();
		this.setMainMenu();
		this.setFindLocation();
		this.setArticleVideoPlayerSizes();
		this.setArticleIframesSizes();
		this.clearArticle();
		this.setMovieVoteLine();
		this.setFindMe();
		this.setActiveTab();



		if ( this.location_city ) {
			
			var that = this;
			
			$('option[value='+ this.location_city +']').attr('selected','selected');
			setTimeout(function(){
				that.jSwitchCityCinema.change(); 	
			},10);
			
		}

		var that = this;
		
		this.tabs_switcher.bind('click', function(){

			if($(this).hasClass('real-link')){
				window.location = $(this).attr('href');
			}
			else {

				var tabid = $(this).attr('rel');
				that.tabs_switcher.removeClass('active');

				$(this).addClass('active');
				that.tabs.hide();
				$('#'+$(this).attr('rel')).show();

				window.location = '#tab:'+tabid;
			}
			return false;
		});

		$(window).resize( function(){
			that.setArticleVideoPlayerSizes();
			that.setArticleIframesSizes();
		});

		if(that.jLoadMore.length > 0){
			$(window).scroll( function(){
				var p = that.jLoadMore.position();
				
				if( p != null){
					if( $(window).scrollTop() + $(window).height() + 800 > p.top ){
						that.jLoadMore.trigger('click');
					} 
				}
			});
		}

		
		$(this.jLoadMoreRef).live('click', function(){


			// if( go == true ){
			// 	go = false;
			// 	var link = $(this).attr('href');
			// 	window.location.href = link;
			// }
			// else {
				//window.location.hash = $(this).data('hash');
				var link = $(this).attr('href');
				//go = true;
				//var elt = $(this); 
				//setTimeout(function(){ 
					//elt.click(); 
					window.location.href = link;
				//}, 10);
				return false;
			//}
		});
		
		$(this.jTrailersListLink).live('click',function(){ 
			that.recordOutboundLinkTrailersList($(this));
		});
			
		$(this.jTrailerList).live('click',function(){
			that.recordOutboundLink($(this));
		});

		this.jSwitchCityCommon.bind('change', function(){
			var loc = $(this).val();
			var loc_html = $("option:selected").text();
			var url = $(this).data('url');

			$.ajax({
				url: base_url + 'mobile/ajax/savestate',
				data: 'state=' + loc + '&statename=' + loc_html,
				success: function(data) {
					window.location.reload();
				}
			});
			
		});

		this.jFindCinemaLocationSwitcher.bind('click',function(e){
			e.preventDefault();
			if(that.goodForWebkitTransitions()) {
				$(that.jSwitchCityCinema).focus();
			}
			else {
				if(that.findlocation_state == false){
					that.findlocation_state = true;
					that.showFindLocation();
				} else {
					that.findlocation_state = false;
					that.hideFindLocation();
				}
			}
		});

		this.jMovieLocationSwitcher.bind('click',function(e){
			e.preventDefault();

			if(that.goodForWebkitTransitions()) {
				$(that.jSwitchCityCommon).focus();
			}
			else {
				if(that.findlocation_state == false){
					that.findlocation_state = true;
					that.showFindLocation();
				} else {
					that.findlocation_state = false;
					that.hideFindLocation();
				}
			}
		});

		this.jSwitchCityCinemaNearest.bind('change', function(){
			var loc = $(this).val();
			var loc_html = $("option:selected").text();

			$.ajax({
				url: base_url + 'mobile/ajax/savestate',
				data: 'state=' + loc + '&statename=' + loc_html,
				success: function(data) {
					window.location.reload();
				}
			});

		});

		this.jSwitchCityCinema.trigger('change');

		this.jSwitchCityCinema.bind('change', function(){

			var loc = $(this).val();
			var loc_html = $("option:selected").text();

			window.location.hash = 'city:'+loc;

			if (loc == 'all') {
				$(".location_subtitle").show();
				$(".location_wrapper").show();
				$("#location_title").html("Nationwide");

				$.ajax({
					url: base_url + 'mobile/ajax/savestate',
					data: 'state=' + loc + '&statename=' + loc_html
				});

			} else {
				$(".location_subtitle").hide();
				$(".location_wrapper").hide();
				$(".location_wrapper[data-location='"+loc+"']").show();
				$("#location_title").html(loc_html);
				$.ajax({
					url: base_url + 'mobile/ajax/savestate',
					data: 'state=' + loc + '&statename=' + loc_html,
				});
			}

			that.findlocation_state = false;
			that.hideFindLocation();
		});

		// Search Bar Switching
		this.jSearchBarSwitcher.bind('click', function(e){
			e.preventDefault();

			if(that.serach_bar_state == false){
				that.serach_bar_state = true;
				that.showSearchBar();
			} else {
				that.serach_bar_state = false;
				that.hideSearchBar();
			}
		});

		// Main Menu Switching
		this.jMainMenuSwitcher.bind('click', function(e){
			e.preventDefault();

			if(that.mainmenu_state == false){
				that.mainmenu_state = true;
				that.showMainMenu();
			} else {
				that.mainmenu_state = false;
				that.hideMainMenu();
			}
		});

		// Set Location Bar Switching
		this.jFindLocationSwitcher.bind('click', function(e){
			e.preventDefault();

			if(that.findlocation_state == false){
				that.findlocation_state = true;
				that.showFindLocation();
			} else {
				that.findlocation_state = false;
				that.hideFindLocation();
			}
		});

		this.back.bind('click',function(e){
			e.preventDefault();
			history.back(-1);
		});

		$(this.jLoadMore).live('click', function(e) {
			e.preventDefault();
			
			if(that.loading_content == false){
				that.loading_content = true; 
				
				var filter = $(this).data("filter");
				var subfilter = $(this).data("subfilter");
				var page = $(this).data("page");
				var url = $(this).data("url");
				var btnhtml = $(this).html();
				var append_block = $(this).data('wrapper');
				var keyword = $(this).data('keyword');
				var btn_loading_text = $(this).data('buttontext') ? $(this).data('buttontext') : that.btn_loading_html;

				$(this).html(btn_loading_text).addClass("ajax-loading");
				
				var thatclick = this;

				window.location.hash = page;

				$.ajax({
					url: url,
					data: 'page=' + page + ( keyword ? '&q='+keyword : ''),
					success: function(data) {
						
						that.loading_content = false;

						data = $(data).filter(".content");
						
						if($('li',data).length > 0){
							$('#'+append_block).append(data.html());
							$(thatclick).removeClass("ajax-loading").html(that.btn_html).data("page", $(thatclick).data("page")+1);

							

						} else {
							that.jNoMoreToLoad.show();
							that.jLoadMore.hide();
						}
					},
					error: function(x, msg, e) {
						$(thatclick).remove();
					}
					
				});
			}
		});
	
		this.jFindMe.bind('click',function(e){
			e.preventDefault();
			
			var action = $(this).data('action');
			var url = $(this).data('url');


			$.geolocation.find(function(latlng){

				var lat = parseFloat(latlng.latitude);
				var lng = parseFloat(latlng.longitude);

		  		$.ajax({
					url: base_url + 'mobile/ajax/saveposition',
					data: 'lat=' + lat + '&lng=' + lng,
					success: function(data) {
						switch(action){
							case 'reload':
								location.reload(true);
								break;
							case 'replace':
								location.replace(url);
								break;
						}
					},
					error: function(x, msg, e) {
						console.debug("data save error");
					}

				});

			}, function(){
			   alert("Your device doesn't support geo location");
			});
		})

		this.jSearchByGenre.bind('change',function(){
			var genre = $(this).val().toLowerCase();
			that.jSearchBarSwitcher.first().trigger('click');
			setTimeout( function(){
				var filter = '';
				var section = '';

				if( window.location.href.match('now-playing') ) section = 'now-playing';
				if( window.location.href.match('coming-soon') ) section = 'coming-soon';
				if( window.location.href.match('trailers') ) {
					section = 'trailers';
					if( window.location.href.match('now-playing') ) filter = '/now-playing';
					if( window.location.href.match('coming-soon') ) filter = '/coming-soon';
				}

				if( window.location.href.match('top_rated_users') ) filter = '/top_rated_users';
				if( window.location.href.match('top_rated_flicks') ) filter = '/top_rated_flicks';
				if( window.location.href.match('newest') ) filter = '/newest';
				if( window.location.href.match('az') ) filter = '/az';
				if( window.location.href.match('release_date') ) filter = '/release_date';
				if( window.location.href.match('thumbs') ) filter = '/thumbs';
				if( window.location.href.match('latest') ) filter = '/latest';
				
				if( genre == 'all genres' ) {
					window.location = '/' + section + filter + '/';
				} else {
					window.location = '/' + section + filter + '/' + genre;
				}

			},250);
		});

		this.jMovieVote.bind('click',function(e){
			e.preventDefault();
			
			if(that.voting_state == false){
				that.voting_state = true;
				
				var vote = $(this).data("vote");
				var href = $(this).data("link");
				var name = $(this).data("name");
				
				that.jVoteReply.fadeOut();
				that.jVoteResult.fadeOut().parent().addClass('active');
				
				$.ajax({
					url: href,
					data: 'vote=' + vote + '&name=' + name,
					success: function(msg) {
						switch(vote){
							case 0:
								try{
						        	var pageTracker = _gat._getTracker("UA-4976087-3");
						        	pageTracker._trackEvent('Movie Votes Up', name);
						      	} catch(err) {}

								that.jVoteReply.empty().html( that.jVoteReply.data('thumbdown') ).fadeIn();
								break;
							case 1:
								try{
						        	var pageTracker = _gat._getTracker("UA-4976087-3");
						        	pageTracker._trackEvent('Movie Votes Down', name);
						      	} catch(err) {}

								that.jVoteReply.empty().html( that.jVoteReply.data('thumbup') ).fadeIn();
								break;
						}

	          			that.jVoteResult
	          				.removeClass('active')
	          				.empty()
	          				.html( msg.talk.percent + '<span class="percent">%</span>' )
	          				.fadeIn()
	          				.parent()
	          				.removeClass('active');
	          			
	                  	jj.cookie('vote_' + msg.talk.movie_id, vote, {
	                    	path: '/',
	                      	expires: 365
	                  	});

	                  	that.voting_state = false;
					}
				});
			}
			
		});

		this.jAddCinema.bind('click',function(e){
			e.preventDefault();

			var action = $(this).data('action');
			var cinema = $(this).data('cinema');
			var flicks_login = $(this).data('flicks_login');
		
			$.ajax({
				url: base_url + 'ajax/favcinema/' + action,
				data: 'cinema=' + cinema + '&flicks_login=' + flicks_login,
				success: function(msg) {
					console.log( msg );
					/*
					if (msg == 'success') {
						$(self)
							.val( $(self).data("action") == 'set' ? 'Remove from favourites' : 'Add to favourites' )
							.data("action", $(self).data("action") == 'set' ? 'remove' : 'set');
					}
					*/
				}
			});
		});
	},

	setFindMe: function(){
		//console.log( $.geolocation );
		//if ($.geolocation.support() == false) this.jFindMe.hide();
	},

	setArticleVideoPlayerSizes: function(){
		this.jArticleVideoPlayer.each(function(){
			var o = $(this);
			var i_width = o.attr('width');
			var i_height = o.attr('height');

			var window_width = $(window).width();

			var new_width = window_width - 20;
			var new_height = i_height*new_width/i_width;

			$(this).attr('width', new_width).attr('height',new_height).children('embed').attr('width', new_width).attr('height',new_height);
		});
	},

	setArticleIframesSizes: function(){
		this.jArticleIframe.each(function(){
			var a = $(this);
			var i_width = a.attr('width');
			var i_height = a.attr('height');

			var window_width = $(window).width();

			var new_width = window_width - 20;
			var new_height = i_height*new_width/i_width;

			$(this).attr('width', new_width).attr('height',new_height);
		});
	},

	clearArticle: function(){
		this.jArticle.each(function(){
			$('div.wp-caption', this).css({'width': 'auto'});
		})
	},

	setSearchBar: function(){
		var sb_height = this.jSearchBar.height();
		this.jSearchBar.css({'display':'block','margin-top': '-' + sb_height + 'px'});
	},
	showSearchBar: function(){
		if(this.goodForWebkitTransitions() && this.cssTransitions) {
			this.jSearchBar.removeClass('hide').addClass('t-searchbar show');
		} else {
			var sb_height = this.jSearchBar.height();
			this.jSearchBar.removeClass('hide').css({
				'margin-top':'0px',
				'margin-bottom': '-'+sb_height+'px'
			});
		}
	},
	hideSearchBar: function(){
		if(this.goodForWebkitTransitions() && this.cssTransitions) {
			this.jSearchBar.removeClass('show').addClass('hide');
		} else {
			var sb_height = this.jSearchBar.height();
			this.jSearchBar.addClass('hide').css({
				'margin-bottom':'auto',
				'margin-top': '-' + sb_height + 'px'
			});
		}
	},

	setMainMenu: function(){
		var mm_height = this.jMainMenu.height();
		this.jMainMenu.css({'display':'block','margin-top': '-' + mm_height + 'px'});
	},
	showMainMenu: function(){
		if(this.goodForWebkitTransitions() && this.cssTransitions) {
			this.jMainMenu.removeClass('hide').addClass('t-mainmenu show');
		} else {
			var mm_height = this.jMainMenu.height();
			this.jMainMenu.removeClass('hide').css({
				'margin-top':'0px',
				'margin-bottom': '-'+mm_height+'px'
			});
		}
	},
	hideMainMenu: function(){
		if(this.goodForWebkitTransitions() && this.cssTransitions) {
			this.jMainMenu.removeClass('show').addClass('hide');
		} else {
			var mm_height = this.jMainMenu.height();
			this.jMainMenu.addClass('hide').css({
				'margin-bottom':'auto',
				'margin-top': '-' + mm_height + 'px'
			});
		}
	},

	setFindLocation: function(){
		var fl_height = this.jFindLocation.height();	
		this.jFindLocation.css({'display':'block','margin-top': '-161px'});
	},
	showFindLocation: function(){
		if(this.goodForWebkitTransitions() && this.cssTransitions) {
			this.jFindLocation.removeClass('hide').addClass('t-popout show');
		} else {
			var fl_height = this.jFindLocation.height();
			this.jFindLocation.removeClass('hide').css({
				'margin-top':'0px',
				'margin-bottom': '-'+fl_height+'px'
			});
		}
	},
	hideFindLocation: function(){
		if(this.goodForWebkitTransitions() && this.cssTransitions) {
			this.jFindLocation.removeClass('show').addClass('hide');
		} else {
			var fl_height = this.jFindLocation.height();
			this.jFindLocation.removeClass('show').addClass('hide');
			this.jFindLocation.addClass('hide').css({
				'margin-bottom':'auto',
				'margin-top': '-' + fl_height + 'px'
			});
		}
	},

	goodForWebkitTransitions: function(){
		if (this.uagent.search('iphone') > -1) return true;
		else if (this.uagent.search('ipod') > -1) return true;
		else if (this.uagent.search('ipad') > -1) return true;
	   	else return false;
	},

	setMovieVoteLine: function(){
		var that = this;
		this.jMovieVoteLine.each(function(){
			var thumbup_text = $(this).data('thumbup');
			var thumbdown_text = $(this).data('thumbdown');
			var movie_id = $(this).data('movieid');

			if( jj.cookie('vote_'+movie_id) == '1' ) that.jVoteReply.empty().html(thumbup_text);
			if( jj.cookie('vote_'+movie_id) == '0' ) that.jVoteReply.empty().html(thumbdown_text);

		});
	},

	setActiveTab: function(){
		if (this.tab != '' && $("a[rel='" + this.tab + "']").length > 0) {
			var that = this;
			setTimeout(function(){
				$("a[rel=" + that.tab + "]").trigger('click');
			},100);
		}
	},

	recordOutboundLinkTrailersList: function(elt) {

		var href = elt.attr('href');
		var category = elt.data('category');
		var action = elt.data('action');
		var hash = window.location.hash;

    	try{

	        $.ajax({
	          url: '/mobile/ajax/set_trailers_position/?p=' + hash.split('#')[1],
	          success: function(data) {
	            console.log( data );
	          }
	        });   

        	var pageTracker = _gat._getTracker("UA-4976087-3");
        	pageTracker._trackEvent(category, action);
        	setTimeout('document.location = "' + href + '"', 100)
      	} catch(err) {}
      	
      	return false;
    },

    recordOutboundLink: function(elt) {
		
		var href = elt.attr('href');
		var category = elt.data('category');
		var action = elt.data('action');

    	try{
        	var pageTracker = _gat._getTracker("UA-4976087-3");
        	pageTracker._trackEvent(category, action);
        	//setTimeout('document.location = "' + link.href + '"', 100)
      	} catch(err) {}
      	
      	return false;
    }
}

