//application object
var CI = {};

CI.columnHeights = function() {
   var minHeight, matchedHeight;
  if($("div.col1").innerHeight() > $("div.col2").innerHeight()) {
    minHeight = $(".col1").innerHeight();
  };
  if($("div.col1").innerHeight() < $("div.col2").innerHeight()) {
    minHeight = $(".col2").innerHeight();
  };
  $(".content-container .center-column").css("min-height",minHeight+50);
  matchedHeight = $(".content-container .center-column").height();
	//IE7 heights
    if(!Modernizr.hashchange) {
	$(".content-container .left-side-outer").height($("div.col1").innerHeight());
	$(".content-container .right-side-outer").height(matchedHeight);
	//Everyone else
    } else {
	delayedChange = function() {
		matchedHeight = $(".content-container .center-column").height();
		$(".content-container .left-side-outer").height($("div.col1").height());
		$(".content-container .right-side-outer").height(matchedHeight);
	};
	//need a delay to allow social modules to load
	setTimeout("delayedChange()",1000);
  }
  
};

CI.featureDividerLast = function() {
	var col1Class = $("div.col1").children().last().attr("class");
	if (col1Class != "features-secondary") {
	$("div.col1").children().last().addClass("features-last");
}
	$("div.col2").children().last().addClass("features-last");
};


CI.showSocialNetworks = function() {
	var timer; 
	var fbInclude = '<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fcinemax&amp;width=300&amp;colorscheme=dark&amp;show_faces=false&amp;stream=true&amp;header=false&amp;height=388" scrolling="no" frameborder="0" style="background: #000; border: 0; overflow:hidden; width:300px; height:388px;" allowTransparency="false"></iframe>';	
	$(".utility-nav #micro-twitter, .utility-nav #micro-fb").bind("mouseover", function() {
		$("div.social-content").fadeIn("fast");
		window.clearTimeout(timer);
		if($(this).attr("id") === "micro-twitter") {
			$("#overlay-twitter").show();
			$("#overlay-fb").hide();
		} else {
			$("#overlay-fb").html(fbInclude).show();
			$("#overlay-twitter").hide();
		}
	});
	$(".utility-nav #micro-twitter, .utility-nav #micro-fb").bind("mouseout", function() {
			timer = setTimeout('$("div.social-content").fadeOut("fast")',500);
	});
	$("div.social-content").bind("mouseover", function() {
			window.clearTimeout(timer);
	});
	$("div.social-content").bind("mouseout", function() {
			timer = setTimeout('$("div.social-content").fadeOut("fast")',500);
	});
};

CI.megaMenus = function() {
   //helper functions
   var currentMenu, close; 
   var menuTimer = function(menu) {
     openMenu = $(".mega-menu "+menu);
     close = window.setTimeout('openMenu.fadeOut("fast", function() {currentMenu = null});', 500);
   };
   var cancelTimer = function() {
     if(close) {
       window.clearTimeout(close);
       close = null;
     };
   };
   var closeCurrentMenu = function() {
     if(currentMenu != null) {
       currentMenu.hide();
       currentMenu = null;
     };
   };
   
   //Kill top level links if this is a touch device
   if(Modernizr.touch) {
		$("li.large").children("a").click(function() {return false});
   };
 
  //touch vs mouse 
  if(Modernizr.touch) {
    $("#main-menu-og").bind("touchend", function() {
		$(".main-nav li.large").removeClass("active");
		$(this).toggleClass("active");
		$("#og-menu").show();
		$("#movies-menu").hide();
		$("#late-night").hide();
    });
  } else {
  	$("#main-menu-og").bind("mouseenter", function() {
  	  closeCurrentMenu();
  	  cancelTimer();
  	  $(".mega-menu #og-menu").fadeIn("fast");
  	  currentMenu = $(".mega-menu #og-menu");
  	});
  	$("#main-menu-og").bind("mouseleave", function() {
  	  menuTimer("#og-menu");
  	});
	};
	
	if(Modernizr.touch) {
  	$("#main-menu-movies").bind("touchend", function() {
		$(".main-nav li.large").removeClass("active");
		$(this).toggleClass("active");
		$("#movies-menu").show();
		$("#og-menu").hide();
		$("#late-night").hide();
  	});
	} else {
  	$("#main-menu-movies").bind("mouseenter", function() {
  	  closeCurrentMenu();
  	  cancelTimer();
  	  $(".mega-menu #movies-menu").fadeIn("fast");
  	  currentMenu = $(".mega-menu #movies-menu");
  	});
  	$("#main-menu-movies").bind("mouseleave", function() {
  	  menuTimer("#movies-menu");
  	});
	};
	
	if(Modernizr.touch) {
		$("#main-menu-latenight").bind("touchend", function() {
			$(".main-nav li.large").removeClass("active");
			$(this).toggleClass("active");
			$("#og-menu").hide();
			$("#movies-menu").hide();
			$("#late-night").show();
		});
	} else {
		$("#main-menu-latenight").bind("mouseenter", function() {
		  closeCurrentMenu();
		  cancelTimer();
		  $(".mega-menu #late-night").fadeIn("fast");
		  currentMenu = $(".mega-menu #late-night");
		});
		$("#main-menu-latenight").bind("mouseleave", function() {
		  menuTimer("#late-night");
		});
	};
	
	//if user is on a mega menu don't close
	$(".mega-menu #og-menu").bind("mouseenter", function() {
	  $("#main-menu-og").addClass("main-nav-open");
	  cancelTimer();
	});
	$(".mega-menu #movies-menu").bind("mouseenter", function() {
	  $("#main-menu-movies").addClass("main-nav-open");
	  cancelTimer();
	});
	$(".mega-menu #late-night").bind("mouseenter", function() {
	  $("#main-menu-latenight").addClass("main-nav-open");
	  cancelTimer();
	});
	$(".mega-menu #og-menu, .mega-menu #movies-menu, .mega-menu #late-night").bind("mouseleave", function() {
	  thisMenu = "#"+$(this).attr("id");
	  menuTimer(thisMenu);
	  $(".main-nav li.large").removeClass("main-nav-open");
	});
};

CI.ajaxTabs = function() { 
	//hashify the links if needed
	tabLinks = $(".series-menu li");
	tabLinks.removeClass("active");
	tabLinks.each( function() {
		link = $(this).children("a").attr("href");
		//make sure the hash isn't already there
		if(link.search("#") === -1) {
			//don't hashify video on ipad
			if(link.search("video") === -1) {
				$(this).children("a").attr("href","#"+$(this).children("a").attr("href"));
			} 
			if(link.search("video") > 0) {
				if(!Modernizr.touch) {
				$(this).children("a").attr("href","#"+$(this).children("a").attr("href"));
				}
			}
		}
	});

	//close tab container button 
	$(".tab-container .close a").click(function() {
	  $(".tab-container").hide();
	  $("#tab-content").hide().empty();
	  $(".series-menu li").removeClass("active");
	});
};

//fades in the CDM, fires tab specific init functions after fade
CI.openCloseContentDisplayModules = function(tab) { 
	//first, move the window to show CDM if required
	if($("body").scrollTop() < 50 ) {
		//don't animate ipad, too choppy...
		if(Modernizr.touch) {
			$("html, body").scrollTop(500);
		} else {
			$("html, body").animate({scrollTop:500},500);
		}
	};
	//do display animation
	$(".tab-container").fadeIn(400, function() {
		$("#tab-content").hide().fadeIn(400, function() {
			//after content has faded in, run any section specific init functions
			switch(tab) {
				case "episodes":
					CI.episodesCarouselInit();
					break;
				case "video":
					CI.contextualVideoInit();
					break;
				case "photos":
					CI.contextualPhotosInit();
					break;
				case "extras":
					$("p.socialItems").fadeIn("slow");
					break;
				case "cast-crew":
					$("p.socialItems").fadeIn("slow");
			}
		});
	}).addClass("open");
	//highlight a tab
	if(tab) {
		$(".series-menu li").removeClass("active");
		$(".series-menu #"+tab).addClass("active");
	}
};

CI.contextualPhotosInit = function() {
	$('#carousel').carouFredSel({
	circular: false,
	infinite: false,
	width: 930,
	height:425,
	padding: 0,
	items: 1,
	align: false,
	prev: '#carousel-previous',
	next: '#carousel-next',
	auto: false
	})
};

//initialize the extras carousel	
CI.extrasCarouselPosition;
CI.extrasTabInit = function(id) {
	//bind thumbs for carousel position
	$("#navList div").unbind().bind('click', function() {
        CI.extrasCarouselPosition = $("#navList").triggerHandler("currentPosition");
    });

	extrasCarousel = $('#navList').carouFredSel({
	circular: false,
	infinite: false,
	width: 825,
	height:140,
	items: {
		items:5,
		width:150
	},
	align: false,
	prev: '#arrowLeft',
	next: '#arrowRight',
	auto: false,
	onCreate: function() {
		//highlight tab
		$("#"+id).addClass("selected");
		//move carousel
		$("#navList").trigger("slideTo", [CI.extrasCarouselPosition,0,true,{fx:"fade", duration:0}]);
	}
	})
};

CI.carouselHomepage = function() {
  var rampsPosition = 0;
  var ramp = $("#color-ramp");
  var ramps = $(".ramp").length;
  $('.carousel div#slider').nivoSlider({
    effect:'slideInLeft',
    effectPrevious: 'slideInRight',
    effectNext: 'slideInLeft',
    keyboardNav:true,
	manualAdvance:true,
    animSpeed:200,
    pauseOnHover:true,
    pauseTime:4000,
    directionNav:true,
    directionNavHide:false,
    captionOpacity:1,
	afterChange: function() {

	},
	afterLoad: function() {

	},
    beforeChange: function() {
		rampsPosition = $('.carousel div#slider').data('nivo:vars').currentSlide;
    	if(rampsPosition === (CI.rampsArray.length-1)) {
			if(Modernizr.canvas) {
				$(".ramp").eq(CI.rampsArray.length-1).fadeOut("fast");
				$(".ramp").eq(0).fadeIn("fast");
			} else {
				$(".ramp").eq(CI.rampsArray.length-1).hide();
				$(".ramp").eq(0).show();
			};
			rampsPosition = 0; 
		} else {;
			//fade only on non-ie browsers
			if(Modernizr.canvas) {
				$(".ramp").fadeOut("fast");
				$(".ramp").eq(rampsPosition+1).fadeIn("fast");
			} else {
				$(".ramp").hide();
				$(".ramp").eq(rampsPosition+1).show();
			};
    	}	
    }
  });
};

//Moves the homepage carousel buttons to to the correct place in the dom
CI.carouselNavigation = function() {
  navButtons = $(".nivo-directionNav").detach();
  if(navButtons) {
    navButtons.appendTo(".header-wrapper");
  }; 
};

//Homepage calendar slice
CI.scheduleDayPicker = function() {
  //build day picker
  var currentDayNumbers = [];
  var x = parseInt(currrentDay);
  var y =0;
  var weekdays = "";
  for(i=0;i<8;i++) {
	if(x+i <= 7) {
		currentDayNumbers[i] = x+i;
	} else {
		currentDayNumbers[i] = y;
		y++;
	};
	if(currentDayNumbers[i] !== 7) {
		weekdays = weekdays+"<li id="+dayWeek[currentDayNumbers[i]]+" class="+currentDayNumbers[i]+">"+dayWeek[currentDayNumbers[i]]+"</li>";
	}
  }
  $("#days p:first").after("<ul><li id=\"dateChange\" class=\"selected\">"+dayWeek[currentDayNumbers[currrentDay]]+"</li>"+weekdays+"</ul>");
  
  var day, changeText, shortenText, currentDayText, listItems;
  var selectedMenuDay;
  $('#days ul li').eq(1).css('padding-top', '6px');
  $('#days ul li').eq(1).addClass("subSelected");
  $('#days ul li').eq(7).css('padding-bottom', '24px');
  menu = $("#days ul");
  menus = $("#days ul li").not(':first');


    //hide and show the days dropdown
  
  menu.mouseover( function() {
	menus.show();
  });

  menu.mouseout(   function() {
	  listItems = $(this).children();
	  //filter out the selected element from the LI children array
	  listItems = listItems.not($(".selected"));
	  listItems.hide();
    });
	
	menus.bind("click", function() {
		menus.hide();
	});
 
  
  //bind click to change schedule day
menu.children().each(function() {
       if ($(this).attr("class") != "selected") {
    $(this).click(function() {
      day = $(this).attr("id");
      for(i=0;i<8;i++) {  
  if(day == dayWeek[i] ) {    
     $("#days ul li").removeClass("subSelected");
      $(this).addClass("subSelected");
   document.getElementById('dateChange').innerHTML = day;
      $("#days ul li.selected").text(day);
       $("div.daily-content").hide();
       $(this).children("li.selected").show();
      $("."+day).show();
        shortenText();   
      }
 }     
 
    });
    }
  });



  currentDayText = $("."+currrentDay).text().toLowerCase();
  menu.children("li:first").text(currentDayText);
  $("div.daily-content").hide();
  $("."+currentDayText).show();
  if(!day) { day = currentDayText };
  //shorten text to fit in slice
  shortenText = function() {
	$("div.daily-content."+day+" ul li").each(
		function() {
			generatedText = $(this).find("a").text();
			if(generatedText.length > 38) {
				generatedText = generatedText.substr(0,35);
				generatedText = generatedText+"...";
				$(this).find("a").text(generatedText);
			}
		}
		
	);
$("div.daily-content."+day+" ul").children().eq(2).addClass("last");	
  };
  shortenText();
  //adjust the text based on number of items
  changeText = function() {
  	 
        if($("div.daily-content."+day+" ul").children().length >= 4) {
        	
                $(".daily-content li").css("width","114px");
                $(".daily-content span.time, .daily-content span.timezone").css("font-size","14px");
                $(".daily-content span.title").css("font-size","12px");
        } else {
                $(".daily-content li").css("width","170px");
                $(".daily-content span.time").css("font-size","22px");
                $(".daily-content span.timezone, .daily-content span.title").css("font-size","14px");
        };
        //$(".daily-content li").eq(2).addClass("last");  
  };
  //uncomment next line to bring back 4 elements at a time to schedule slice
  //changeText();

};

CI.providerList = function() {

  $("#selectElement").change(function() {
        var url = $(this).val(); 
        if (url != "Select Provider") { 
			var s=s_gi(s_account);
			s.linkTrackVars='events,server';
			s.linkTrackEvents='event7';
			s.server='cinemax.com';
			s.events='event7';
			s.tl(this,'o','Event Tracking');
        
			if(Modernizr.touch) {
				document.location = url
			} else {
				window.open(url);
			}
        } 
    });
	
};

CI.initCastCarousel = function(id) { 
		castCarousel = $("#cast").carouFredSel({
		width: "variable",
		circular: false,
		infinite: false,
		items: {
			items:8,
			width:106
		},
		scroll: 8,
		align:"left",
		auto: false,
		prev: ".arrows#left",
		next: ".arrows#right",
		onCreate: function(items) {	
			//highlight the thumb
			$("#"+id).addClass("active");
			//slide the carousel to highlight
			$("#cast").trigger("slideTo", [CI.castCarouselPosition,0,true,{fx:"fade", duration:0}]);
			
		}		
	});
};

CI.initCrewCarousel = function() { 
		crewCarousel = $("#crew").carouFredSel({
		width: 840,
		scroll: 500,
		circular: false,
		infinite: false,
		align:"left",
		auto: false,
		items : {visible: 2},
		prev: ".arrows#left2",
		next: ".arrows#right2",
		onCreate: function() {
			if($("#crew").find("div").length === 1) {
				$("#crew").find("div").css('border-right',0);
			} else {
				$("#crew").find("div").filter(":odd").css('border-right',0);
			}
		}
	});
};

CI.showActorCharacter = function(e) {
	//actor or character? 
	e = e.substring(0,5);
	//Show relevant divs
	if(e === "actor") { 
		CI.actorCharacterSwap("#actor");
	}
	else if(e === "chara") { 
		CI.actorCharacterSwap("#character");
	}
	//no actor or character requested
	else {	
		defaults = function() {
			//show actor info
			CI.actorCharacterSwap("#actor");
			$("#castTab").click();
		};
		//give the DOM a bit of time...
		time = setTimeout('defaults()',1000);
	};	
};

CI.castCarouselPosition;
CI.castCrewInit = function(id) {
	$("#characterTab").unbind().bind("click", function() {
		CI.actorCharacterSwap("#character");	
		return false;
	});
	$("#actorTab").unbind().bind("click", function() {
		CI.actorCharacterSwap("#actor");	
		return false;
	});
	$("#cast img").unbind().bind('click', function() {
        CI.castCarouselPosition = $("#cast").triggerHandler("currentPosition");
    });

	//show character and cast tabs
	CI.showActorCharacter(id);
	
	//this loads the cast carousel
	CI.castCrewSwap(id);
	$("#castTab").click();

};

CI.actorCharacterSwap = function(e) {
	$("#actor, #character").hide();
	$("#characterTab, #actorTab").removeClass("active");
	$("#characterImg, #actorImg").removeClass("active");
	$(e).fadeIn("fast");
	if(e === "#actor") {	
		$("#actorTab").addClass("active");
		$("#actorImg").addClass("active");
	} else {
		$("#characterTab").addClass("active");
		$("#characterImg").addClass("active");
	};
};

CI.castCrewSwap = function(id) {
	$("#castTab, #crewTab").click(function() {
		$("#castTab, #crewTab").removeClass("active")
		$(this).addClass("active");
		CI.initCastCarousel(id);
		
		if($(this).attr("id") === "castTab") {
			$(".arrows#left2, .arrows#right2").hide();
			$(".caroufredsel_wrapper").css({"top":0,"height":"85px"});
		} else {
			CI.initCrewCarousel();
			$(".arrows#left, .arrows#right").hide();
			$(".caroufredsel_wrapper").css({"top":-85,"height":"85px"});
		};
	});
};

CI.episodesCarouselInit = function() {
	$('#all-seasons').carouFredSel({
	circular: false,
	infinite: false,
	items: {visible:1,minimum:1},
	prev: '#prev1',
	next: '#next1',
	onCreate: function(items) {
		
    },
	scroll: { 
		onBefore: function(oldItems, newItems) {
			newItems.each(function() { 
				var div_name = this.id;
				switchSeasons(div_name);
				});
			}
		},
	auto: false
})

$("#season-nav li").click(function(){
  var new_season = ("#all-seasons div#" + this.id);
  $("#all-seasons").trigger("slideTo", [$(new_season)]); 
  }).css("cursor","pointer");
    
};

CI.contextualVideoInit = function(){
$('#video-list').carouFredSel({
	circular: false,
	infinite: false,
	direction: "down",
	width: 270,
	height: 405,
	align: false,
	padding: 0,
	items: 4,
	prev: '#arrow-up',
	next: '#arrow-down',
	auto: false,
	onCreate: function() {
		pos = getParameterByName("bctid");
		pos = $("#video"+pos);
		$("#video-list").trigger("slideTo", [pos,0,true,{fx:"fade", duration:0}])
	}
})

function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
};

if(Modernizr.touch) {
	document.getElementById("arrow-up").style.visibility="visible";
	document.getElementById("arrow-down").style.visibility="visible";
	document.getElementById("video-nav").style.visibility="visible";
	parseURLId();
	var baseLink = document.URL;
	if(baseLink.indexOf("?") != -1) {
		baseLink = baseLink.substring(0,baseLink.indexOf("?"));
	}

	$('#video-list li').bind("touchend", function() {
		videoId = $(this).attr("id").split("video")[1];
		var refreshLocation = baseLink+"?bctid="+ videoId;
		document.location=refreshLocation
	});

} else {
		$('.video-list li').bind("click", function() {
		currentVideoIsTVMa = $(this).hasClass('age-gated');
		currentVideoId = $(this).attr("id").split("video")[1];
		CIVideo.updateVideoPlayer();
		highlightCurrent(currentVideoId);
		var videoTitle = $(this).children("p.displayName").html().toLowerCase();
		if (videoTitle.indexOf("<span")!= -1) {
		videoTitle = videoTitle.split("</span>")[1];
		}
		trackVideoLink(videoTitle);
		});
		
		$('.video-list li').bind("mouseover", function() {
			videoId = $(this).attr("id").split("video")[1];
			var spanId = "icon" + videoId;
			if (document.getElementById(spanId).className != "selected") {
				document.getElementById(spanId).style.visibility="visible";
			}
		});
		
		$('.video-list li').bind("mouseout", function() {
			videoId = $(this).attr("id").split("video")[1];
			var spanId = "icon" + videoId;
			document.getElementById(spanId).style.visibility="hidden";
		});
	}


};

//Hides the what's hotmenus in the mega menus on the homepage
CI.hideWhatsHot = function() {
	$(".menus .whats-hot").remove();
	//adjust landing page text location
	$(".menus h5").css('bottom','10px');
	//pull the link from the home icon
	$("ul.main-nav .home").children().remove();
	$(".mega-menu .menus").each( function() {
		//adjust the overall height
		oldHeight = $(this).height();
		$(this).height(oldHeight-37);		
	});
}


function setTooltips() {
	var tooltip, pos, oldtip;
	//deal with touch interfaces
	if(Modernizr.touch) {
		$(".features-explore li").bind("touchend", function() {
			if(oldtip) { oldtip.hide() };
			tooltip = $(this).children("div");
			tooltip.show();
			oldtip = tooltip;
		})
	
	} else {	
		//mouseover
		$(".features-explore li").hover( function() {
			tooltip = $(this).children("div");
			pos = $(this).position();
			tooltip.detach().insertAfter($(this)).fadeIn(200).css({'left':pos.left+100,'top':pos.top+60});
		},
		function() {
			tooltip.detach().appendTo($(this)).hide();
		})
	}
};

CI.loadThumbnails = function(oldItems, newItems) {
	//remove this;
};

function handleNewsletterSubscribe() {
newsletterOmniture();
	
	// this may be confusing and can be taken out
	document.getElementById('submissionresult').innerHTML = "Please wait as we update your subscription...";
	
	//assemble parameters for JQuery get	
	var subscribeForm = document.getElementById('newsletter');
	var email = subscribeForm.elements['emailAddress'].value;
	var newslettername = subscribeForm.elements['newsletterId'].value;
	var urlParameters = {"senderEmailAddress" : email,"nl" : newslettername};
	
	$.get("/apps/submitinfo/maxsubscribe/submit.do", urlParameters, function(data) {
		document.getElementById('submissionresult').innerHTML = data;
	});
	return false;
};

function handleNewsletterSubscribeSchedule() {
	// this may be confusing and can be taken out
	document.getElementById('submissionresult').innerHTML = "Please wait as we update your subscription...";
	
	//assemble parameters for JQuery get	
	var subscribeForm = document.getElementById('newsletter');
	var email = subscribeForm.elements['emailAddress'].value;
	var newslettername = subscribeForm.elements['newsletterId'].value;
	var urlParameters = {"senderEmailAddress" : email,"nl" : newslettername};
	
	$.get("/apps/submitinfo/maxsubscribe/submit.do", urlParameters, function(data) {
		document.getElementById('submissionresult').innerHTML = data;
	});
	return false;
};

function newsletterOmniture() {
        var s=s_gi(s_account);
        s.linkTrackVars=tracking_vars;
        s.linkTrackEvents='event3';
        s.server='cinemax.com';
        s.events='event3';
        s.tl(this,'o','Event Tracking');
}


//backbone main vars
//blocks CDM from displaying until told otherwise
CI.blockCDM = true;
var tabRouter, appView


//global init
$(function(){
	CI.columnHeights();
	CI.featureDividerLast();
	CI.megaMenus();
	CI.showSocialNetworks();
	if($(".tab-container").size()) {
		//hashify the tab links
		CI.ajaxTabs();
	};

	appView = Backbone.View.extend({
		initialize: function() {
			var currentPath = document.location.pathname;
			var currentHash = document.location.hash;
			var currentPathArray  = currentPath.split("/");
			var currentSection = currentPathArray[currentPathArray.length-2];
			if(currentHash === "") {
				//no hash or an empty hash, carry on
					if(CI.blockCDM === false) {
						//CDM block has been taking off, carry on to stage 2
						$("#tab-content").empty().load("tab.html", function() {
							CI.openCloseContentDisplayModules(currentSection);
						});	
					}
			}
		},
		el: $("document")
	});

	tabRouter = Backbone.Router.extend({
		routes: {
		"/movies/:movie/:tab/:file":"showMovie",
		"/:section/:tab/:file":"showSection",
		"/:section/:tab":"showSection",
		"/after-dark/:section/:tab/:file":"showAfterDarkSection"
		},
		showMovie: function(movie,tab,file) {
			if(file === "") { file = "tab.html" };
			$("#tab-content").empty().load("/movies/"+movie+"/"+tab+"/"+file, function() {
				CI.openCloseContentDisplayModules(tab);
			});
		},
		showSection: function(section,tab,file) {
			if(file === "") { file = "tab.html" };
			$("#tab-content").hide().empty().load("/"+section+"/"+tab+"/"+file, function() {
				CI.openCloseContentDisplayModules(tab);
			});	
		},
		showAfterDarkSection: function(section,tab,file) {
			if(file === "") { file = "tab.html" };
			$("#tab-content").empty().load("/after-dark/"+section+"/"+tab+"/"+file, function() {
				CI.openCloseContentDisplayModules(tab);
			});
		}
	});
	
	//init backbone
	new appView();
	new tabRouter();
	try {
		Backbone.history.start()
	} catch(err) {
		Backbone.history.loadUrl()
	}

});

//Cinemax drop down menus plugin
(function( $ ){
  $.fn.CIdropdown = function(options) {
	var dropMenu = this.children("li");
	
	//these are the things the plugin will use as defaults
	var defaults  = {
		'width':'200px',
		'height':'auto'
	};
	
	if(options) {
		var options = $.extend(defaults,options)
	}
	this.css('width',options.width);
	dropMenu.find("ul").css('height',options.height);
	
	//events ("this" always refers to the DOM element you chose when you instatiated the plugin)
	this.hover(
		function() {
		$(this).find("ul").stop(true, true).slideDown(200); 
	},
		function() {
		$(this).find("ul").stop(true, true).slideUp(200); 
	})
	this.click(function() {
		if(!Modernizr.touch) { $(this).find("ul").stop(true, true).hide() };
	})


  };
})( jQuery );
