/*

	13twelve vs. jQuery

	This javascript is the main javascript for the sites actions.

*/

// --------------------------------------------------------------------------------------------------------------

var dfi = function(){
    var isIE6 = false;
    var isIOS = false;
    var isIpad = false;
    function browserTest() {
        //
        // Some browser and OS testing. 
        // 
        // Classes written to the body for good browsers, as there doesn't seem to be a performance hit doing that
        // IE seems to have an incredible performance hit doing that, so use conditional comments for it.
        //
    	if (navigator.appVersion.indexOf("Mac")!=-1) {
    		isMac = true;
    		$('body').addClass("isMac");
    	}
    	function searchVersion(browser) {
    		var dataString = navigator.userAgent;
    		var index = dataString.indexOf(browser);
    		if (index == -1) return;
    		var bVersion = parseFloat(dataString.substring(index+browser.length+1));
    		if (browser = "Firefox") {
    		    return bVersion.toString();
		    } else {
		        return bVersion.toString().split(".")[0];
		    }
    	}
    	// Webkit
    	if ($.browser.webkit) {
    		$('body').addClass("isWebkit");
    	}
    	// Mozilla versioning
    	if ($.browser.mozilla) {
    		$('body').addClass("isMozilla");
    		version = searchVersion("Firefox") || "";
    		if (version <= 3) {
    		    ffHelpers();
    		    $(".ff").css("visibility","visible");
    		} else {
    		    showFontFaceFontsFirefox();
    		}
    		version = version.replace(".","-");
    		$('body').addClass("isMozilla"+version);
    	}
    	// IE versioning
    	isIE = jQuery.browser.msie;
    	if (isIE) {	
    		version = searchVersion("MSIE") || "";
    		isIE6 = (version == 6) ? true : false;
    		ieHelpers();
    		if (isIE6) {
    		    ie6Helpers();
    		}
    	}
    	if( (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)) ) { 
    	    isIOS = true;
        }
        if( (navigator.userAgent.match(/iPad/i)) ) { 
            isIpad = true;
        }
    }
    function defaultValues() {
        //
        // Form inputs with default values
        //
        // take off the default values in the sitewide search and newsletter forms
        $('input[type="text"]').each(function(){
            var initVal = $(this).val();
        	//
        	$(this).focus(function(){
        	    $(this).val("");
        	});
            $(this).blur(function(){
        	    if ($(this).val() == "") {
        			$(this).val(initVal);
        		}
        	});
        });

    }
    function ffHelpers() {
        $("ul.films li:nth-child(3n)").addClass("li3n");
        $("ul.workshops-past li:nth-child(2n)").addClass("li2n");
        $("#search #spotlight article:nth-child(4n+1)").addClass("li4nplus1");
        $("#search #spotlight .videos li:nth-child(4n+1)").addClass("li4nplus1");
        $("#search #spotlight .photos li:nth-child(4n+1)").addClass("li4nplus1");
    }
    function ieHelpers() {
        
        $("ul.films li:nth-child(3n)").addClass("li3n");
        $("ul.workshops-past li:nth-child(2n)").addClass("li2n");
        $("form.contact fieldset ol li:nth-child(2n)").addClass("li2n");
        $("html[dir=rtl] form.contact fieldset ol li:nth-child(2n)").addClass("li2nr");
        $("#search #spotlight article:nth-child(4n+1)").addClass("li4nplus1");
        $("#search #spotlight .videos li:nth-child(4n+1)").addClass("li4nplus1");
        $("#search #spotlight .photos li:nth-child(4n+1)").addClass("li4nplus1");

        $("#press.medias.photos-section ul.thumbnails li:nth-child(4n)").addClass("ieEveryFourthItem");
        $("#press.medias.main ul.items li:nth-child(4n)").addClass("ieEveryFourthItem");
        $("#press.medias.photos-section ul.items li:nth-child(4n)").addClass("ieEveryFourthItem");
        $("#press.medias.videos-section ul.items li:nth-child(4n)").addClass("ieEveryFourthItem");
        $("#press.medias.videos-section ul.videos li").slice(-4).addClass("ieLastFour");
        $("#press.medias.photos-section ul.photos li").slice(-4).addClass("ieLastFour");
        
        
    }
	function ie6Helpers() {
	    //
	    // Gah!
	    //
	}
	function searchBar() {
    // The search bar, click to show and auto hide function
    //
    // Not used anymore
    // Showing the form, openClick()
    // 1. When the form is closed, clicking the submit button opens the form up and shows the text box.
    // 2. It also unbinds the click event, so the next click will submit the form.
    // 3. And triggers a timer function
    //
    // Timer function, timerToClose()
    // 1. on mouseout of the form, start a timer that will trigger closing the form
    // 2. on hover, clear that timer. So whilst hovering, the form will stay open.
    //
    // Closing the form, closeSearch()
    // 1. If nothing has been typed into the search box, close it down and hide the text box
    // 2. Re-initialise the opening function
    // 3. If there has been something typed in, leave it open, the user might still want to search
    // 4. Either way, stop the timer
    //
    
    if ($("#tools form").length > 0) {
      var timer;
      var form = $("#tools form");
      var textbox = $("#tools form input[type='text']");
      //
      function openClick() {
         $("#tools form input[type='submit']").click(function(event){
             event.preventDefault();
             event.stopPropagation();
             $(this).unbind();
             form.animate({
                  width: "209px"
              }, 500).find("input[type='text']").show().focus();
              timerToClose();
         });   
       }
       function closeSearch() {
         if (textbox.val().length == 0) {
             form.animate({
                  width: "44px"
              }, 500).find("input[type='text']").hide();
              openClick();   
         }
         clearTimeout(timer);
       }
       function timerToClose() {
         form.hover(
           function () {
             clearTimeout(timer);
           }, 
           function () {
             timer = setTimeout(closeSearch,2000);
           }
         );
       }
       openClick();
     }
  }
	function spotlightScroll() {
	    // 
	    // The columns scroller in the homepage spotlight section
	    //
	    // inspired by, nay, copied from: http://www.cinematek.be/
	    // though its warping my frikken mind and I can't tell if its actually working the same..
	    //
	    // aScroll is an initial value of how far the page is scrolled to compare to if the page is scrolled.
	    // If the page is scrolled, the scrollColumn function is called, with a param for direction of scroll.
	    //
	    // scrollColumn looks at the columns and adjusts the top margin of the shorter divs, so it appears as if
	    // they stop scrolling with relation to the page. It means less white space below a short column.
	    //
	    // Its magic. Though I'm not convinced by it :-p
	    //
	    function scrollColumn(poss){
        	var scroll = $(window).scrollTop();
        	var footerHeight = 655; // height of the footer + 1px padding bottom + margin bottom of the #spotlight article

        	$("#spotlight.flow > div").each(function(index){    	    
        		var cOffset = $(this).height()-$(window).height()+$(this).offset().top+footerHeight;	
        		if (cOffset-($(this).css('margin-top').replace("px","") * 1)<0){
        			$(this).css('margin-top',scroll+'px');
        		} else {
        			if(poss=='up'){
        				if(scroll>=cOffset){
        					var margin = scroll - cOffset + ($(this).css('margin-top').replace("px","") * 1);
        					$(this).css('margin-top',margin+'px');
        				}
        			} else {
        				var margin = ($(this).css('margin-top').replace("px","") * 1);
        				if(margin>scroll){
        					$(this).css('margin-top',scroll+'px');
        				}
        			}
        		}    		
        	});
        }        
        var aScroll = $(window).scrollTop();      
        $(window).scroll(function() {        
            if(($("#spotlight.flow > div").length>1) && !isIE6){
                var cScroll = $(window).scrollTop();
                if (cScroll>aScroll){
                    scrollColumn('up');
                } else {
                    scrollColumn('down');
                }
                aScroll = $(window).scrollTop();
            }
    	});
	}
	function whatsonCalendar() {
	    // 
	    // The calendar hover tool tip boxes
	    //
	    // On Hover:
	    // 1. Find out the position on the page of the link
	    // 2. Clone the .meta that contains the information, give it an ID, position it with CSS and fade it in. 
	    //    Its appended to the body to beat IE's flawed Z-index implementation.
	    //
	    // On Mouseout:
	    // 1. Fade out the inserted div
	    // 2. Remove it from the DOM
	    //
	    
        $("#whatson .paginator a").live('click', function(event) {
          // load and replace the whatson container

          $.ajax({
            url: $(this).attr("href"), type: 'post',
            success: function(data) { 
              $("#whatson").html(data);
            }
          });

          event.preventDefault();
          event.stopPropagation();
        });

        if (!isIOS) {
            $("#whatson a").live('mouseover mouseout', function(event) {
                if (event.type == 'mouseover') {
                    var position = $(this).offset();
                    if ($('html[dir="ltr"]').length > 0) {
                        $(this).find(".meta").clone().appendTo("body").attr("id","whatsonMeta").css({ left: position.left+26, top: position.top+29 }).fadeIn(150);   
                    } else {
                        $(this).find(".meta").clone().appendTo("body").attr("id","whatsonMeta").css({ left: position.left-179, top: position.top+29 }).fadeIn(150);
                    }
                } else {
                    $("#whatsonMeta").fadeOut(150, function() { $("#whatsonMeta").remove(); });
                } 
            });

        }
	}
	function alertbox() {
	    //
	    // The home page has an alert box that can be closed down
	    //
	    // 1. Fade out the box
	    // 2. On complete, close up the box
	    // 3. On complete, remove it from the DOM.
	    //
	    if($("#alert").length > 0) {
	        $("#alert .close a").click(function(event){
	            event.preventDefault();
	            event.stopPropagation();

              createCookie(""+this.rel+"-alert", "1", 7);

	            $("#alert").animate({
	                opacity: 0
	            }, 200, function(){ 
	                $("#alert").animate({
	                    paddingTop: 0,
    	                paddingBottom: 0,
    	                marginBottom: 0, 
    	                height: 0
	                }, 200, function(){
	                   $("#alert").remove();  
	                });
	            });
	        });
	    }
	}
	function listingClicks() {
	    //
	    // Some blocks want to be clickable and have hover states, yet aren't themselves links - they just contain a link
	    // eg. listings
	    // html 5 links as blocks can't be used, as some of these blocks will contain more than one link
	    //
	    var applyTo = $("#discover .slider li, #spotlight article, section.meet, .article-listing article, .workshops li, .workshops-past li, .films li, .videos li, .photos li, .allseries li, .other-pages li, .jury li").not("#filmfestival.films .allseries li");
	    //
        applyTo.each(function(){
            // find the first link, its assumed that that is the prime link
            var href = $(this).find("a:first").attr("href");
            var target = $(this).find("a:first").attr("target");
            var hover = false;
            var $this = $(this);
            //
            // 1. on hover, add a class, change the pointer, and decorate the link
            // 2. on click, go to to the prime link location
            // 3. .section links inside of these blocks still need to be active
            //
            $this.hover(function(){
                    //$this.addClass("hover").css("cursor","pointer").find("a:first").css("text-decoration","underline");
                    $this.addClass("hover");
                    hover = true;
                }, function () {
                    //$this.removeClass("hover").find("a:first").css("text-decoration","none");
                    $this.removeClass("hover");
                    hover = false;
                }
            ).click(function(event){
                event.preventDefault();                
                if (href != "#" && href != undefined && href.length > 1) {
                    if(target == "_blank") {
                        window.open(href);
                    } else {
                        window.location = href;
                    }
                }
            }).parent().find(".section a, .films_info a").click(function(event){
               event.stopPropagation(); 
            }).hover(function(){
                    if (hover) {
                        //$this.removeClass("hover").find("a:first").css("text-decoration","none");
                        $this.removeClass("hover");
                    }
                }, function () {
                    if (hover) {
                        //$this.addClass("hover").css("cursor","pointer").find("a:first").css("text-decoration","underline");
                        $this.addClass("hover");
                    }
                }
            )
        }); 
        // special case for film festival films all series link
        $("#filmfestival.films .allseries li").each(function(){
            var href = $(this).find("a:first").attr("href");
            var hover = false;
            var $this = $(this);
            //
            $this.find("img").hover(function(){
                    $(this).css("cursor","pointer");
                    $this.addClass("hover");
                    hover = true;
                }, function () {
                    $this.removeClass("hover");
                    hover = false;
                }
            ).click(function(event){
                event.preventDefault();                
                if (href != "#" && href != undefined && href.length > 1) {
                    window.location = href;
                }
            });
        });
        // special case for events listing
        $("#events dl.events dd").each(function(){
            var href = $(this).find("a:first").attr("href");
            var hover = false;
            var $this = $(this);
            //
            $this.hover(function(){
                    $(this).css("cursor","pointer");
                    $this.addClass("hover").prev().addClass("hover");
                    hover = true;
                }, function () {
                    $this.removeClass("hover").prev().addClass("hover");
                    hover = false;
                }
            ).click(function(event){
                event.preventDefault();           
                if (href != "#" && href != undefined && href.length > 1) {
                    window.location = href;
                }
            }).prev().hover(function(){
                    $(this).css("cursor","pointer");
                    $this.addClass("hover");
                    $(this).addClass("hover");
                    hover = true;
                }, function () {
                    $this.removeClass("hover");
                    $(this).removeClass("hover");
                    hover = false;
                }
            ).click(function(event){
                event.preventDefault();            
                if (href != "#" && href != undefined && href.length > 1) {
                    window.location = href;
                }
            });
        });
	}
	function topLink(){
	    //
	    // Scroll to the top of the page on click
	    //
	    if($(".top-link").length > 0) {
	        $(".top-link a").click(function(event){
	            event.preventDefault();
	            if (isIpad) {
	                $("body").scrollTop(0);
	            } else {
	                $.scrollTo("#dfi", 250);
	            }	            
	        });
	    }
	}
	function directionSwitcher() {
	    //
	    // This is just for development, quickly switch the language direction
	    //
	    var dir;
	    if ($('html[dir="ltr"]').length > 0) {
	        $('<a href="#" id="directionSwitcher">ltr to rtl</a>').appendTo("body");
	        dir = "ltr";	        
	    } else {
	        $('<a href="#" id="directionSwitcher">rtl to ltr</a>').appendTo("body");
	        dir = "rtl";
	    }
	    $("#directionSwitcher").click(function(event){
	        event.preventDefault(); 
	        if (dir == "ltr") {
	            $("html").attr("dir","rtl");
	            $(this).text("rtl to ltr");
	            dir = "rtl";
	        } else {
	            $("html").attr("dir","ltr");
	            $(this).text("ltr to rtl");
	            dir = "ltr";
	        }
	    });
	}
    function dropdownBar() {
	    //
	    // Some pages have a hidden list of related items that drops down.
	    // Two main variations:
	    // - click of a h2.dd-title, singular
	    // - click of a link inside of a links bar, can have multiples here...
	    //
	    var open = false;
	    var lists, links, paddingTop, paddingBottom, marginBottom, heights;
	    //
	    function ddToggle(link,list,index) {
            if (!open) {
                openList(link,list,index);
                open = true;
            } else {
                if (link.hasClass("dd-title-open")) {              
                    closeList(link,list);
                    open = false;
                } else {
                    var oldLink = $(".dd-title-open:first");
                    var oldList = lists.filter(":visible");
                    closeList(oldLink,oldList);
                    openList(link,list,index);
                    open = true;
                }
            }
	    }
	    function closeList(link,list,index) {
	        if(!isIE6) {
	            link.removeClass("dd-title-open");
                list.animate({
	                paddingTop: "0px", 
	                paddingBottom: "0px",
	                marginBottom: "-1px", 
	                height: "0px"
	            }, 200, function(){
	                list.css({ borderColor: "#fff" });
	            });
	        } else {
	            ie6Toggler();
	        }
	    }
	    function openList(link,list,index) {
	        if(!isIE6) {
    	        link.addClass("dd-title-open");
                list.css({
                    borderColor: "#e0e0e0"
                }).animate({
                    paddingTop: paddingTop, 
                    paddingBottom: paddingBottom, 
                    marginBottom: marginBottom, 
                    height: heights[index]
                }, 200);
	        } else {
	            ie6Toggler();
	        }
	    }
	    function ie6Toggler(link,list) {
	        // no animations for IE...
	        list.toggle();	            
            link.toggleClass("dd-title-open")
	    }
	    //
	    if ($(".dd-title").length > 0 && $("ul.dd-list").length > 0) {
	        //	        
	        lists = $(".dd-list");
	        links = $(".dd-title");
	        heights = [];
	        //
	        if(!isIE6) {
	            paddingTop = lists.css("paddingTop").replace("px","");
    	        paddingBottom = lists.css("paddingBottom").replace("px","");
    	        marginBottom = lists.css("marginBottom").replace("px","");
    	        //heights = lists.css({ position: "absolute", left: "-9999em", display: "block" }).height();
    	        lists.each(function(index){
    	            heights[index] = $(this).css({ position: "absolute", left: "-9999em", display: "block" }).height();
    	        });
    	        //
    	        //lists.css({ position: "static", left: "auto", padding: "0px", marginBottom: "-1px", height: "0px", display: "block", borderColor: "#fff" });
    	        //
	        }
	        $(".dd-title").click(function(event){	            
	            event.preventDefault();
	            var index = $(".dd-title").index($(this));
	            var list = $(".dd-list").eq(index);
	            if (!$(this).hasClass("dd-title-open")) {
	                list.css({ position: "static", left: "auto", padding: "0px", marginBottom: "-1px", height: "0px", display: "block", borderColor: "#fff" });
                }
                ddToggle($(this),list,index);
                return false;
            });	        
	    }
	}
	function moreContentLinks() {
	    //
	    // Some read more links drop down more content
	    //
	    if($(".moreContent-link").length > 0 && $(".moreContent").length > 0) {
	        // find the elements we're going to use
	        var links = $(".moreContent-link");
	        var lessLinks = $(".lessContent-link");
	        var contents = $(".moreContent");
	        
	        links.each(function(index,value){
	            $(this).click(function(event){
	                event.preventDefault();
	                $(this).animate({ opacity: 0 }, 100, function() {
	        	        contents.eq(index).slideDown(250);
        	        
        	        
	        	        if (map) {
	            			  var center = map.getCenter();
	                    	  google.maps.event.trigger(map, 'resize');
	                    	  map.setCenter(center);
	            		}
	                	
	                });
        	        
	            });
    	    });
    	    
    	    lessLinks.each(function(index,value){
	            $(this).click(function(event){
	                event.preventDefault();
					contents.eq(index).slideUp(250, function() {
						links.eq(index).animate({ opacity: 1 }, 100);
					});
	            });
    	    });
	        
	    }

	}
  function customDD() {
    var open = false;
    $("body").click(function(event){
        bodyClick(event);
    });
    $('body').bind( "touchstart", function(event){
        bodyClick(event);
    });
    $(window).keyup(function(event) {
 		  if (open && event.keyCode == 27) {
 		    hideDD();
 		  }
 		})
    function bodyClick(event) {
 		    if (open) {
                 if ( $(event.target).is('.dd ul li a') ) { return; }
                 if ( $(event.target).is('.dd p') ) { return; }
                 if ( $(event.target).is('.dd p span') ) { return; }
                 event.preventDefault();
                 hideDD();
              }
 		}
    function hideDD() {
 		    open = false;
            $(".dd p.open").removeClass("open").next().addClass("hide");
 		}

    $(".dd").delegate("p", "click", function(event){
        if (open && !$(this).hasClass("open")) {
            $(".dd p.open").removeClass("open").next().addClass("hide");
            $(this).addClass("open").next().removeClass("hide");
            open = true;
        } else {
            $(this).toggleClass("open").next().toggleClass("hide");
            open = !open;
        }
        return false;
    });
  }
  
  var map;
  
     function googleMaps() {
       	if ($("#googlemap").length > 0 && $("#googlemap li").length > 0) {
       		$("#googlemap").css("width","536px").css("height","345px");    		
      		var addresses = [];
      		var hrefs = [];
      		var latLongs = [];
      		var openInfoWindow = false;

      		$("#googlemap li").each(function(){
      			addresses.push($(this).text());
      			hrefs.push( $(this).find("a").attr("href") );
      			latLongs.push( $(this).find("a").attr("rel") );
      		});
            
      		var geocoder = new google.maps.Geocoder();

      		if (geocoder && addresses.length == 1) {
      			geocoder.geocode( { 'address': addresses[0]}, function(results, status) {
      				if (status == google.maps.GeocoderStatus.OK) {
      					map = new google.maps.Map(document.getElementById("googlemap"), {
      						zoom: 18,
      						center: results[0].geometry.location,
      						mapTypeId: google.maps.MapTypeId.SATELLITE
      					});
      					var marker = new google.maps.Marker({
      						map: map,
      						position: results[0].geometry.location
      					});      					

  					    var addressString = addresses[0].replace(" ","+");
  					    var infowindow = new google.maps.InfoWindow({ 
  					        content: '<p><strong>'+addresses[0]+'</strong> <br /><a href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q='+addressString+'" target="_blank">Open in Google Maps</a></p>'
                        });
                        google.maps.event.addListener(marker, 'click', function() {
                            infowindow.open(map,marker);
                        });
                        infowindow.open(map,marker);
                        map.setOptions({ zoom: 15, mapTypeId: google.maps.MapTypeId.ROADMAP });
                        map.panBy(0,-50);

      				}      				
      			});
      			
             } else if (geocoder && addresses.length > 1) {
                 
                var address = "Doha, Qatar";
                var zoom = 11;
                
                // get optionnal zoom and address
                var title = $("#googlemap").attr('title');
                var id = $("#googlemap").attr('class');
                
                var defaultAdress = "Doha, Qatar";
                var addressStr = (title != '') ? title : defaultAdress;
                var zoom = (id != '') ? Number(id.replace(/[^\d\,\.-]/g,'')) : 11;
                 
                geocoder.geocode( { 'address': addressStr}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    map = new google.maps.Map(document.getElementById("googlemap"), {
                      zoom: zoom,
                      center: results[0].geometry.location,
                      mapTypeId: google.maps.MapTypeId.SATELLITE
                    });
                    if(addressStr == defaultAdress) map.panBy(0,-75);  					
                    
                    $.each(addresses, function(index){              	            
                      var latLong = new google.maps.LatLng(latLongs[index].split(",")[0], latLongs[index].split(",")[1]);
  
                      var marker = new google.maps.Marker({
                        map: map,
                        position: latLong
                      });

                      var addressString = addresses[index].replace(" ","+");
                      var infowindow = new google.maps.InfoWindow({ 
                        content: '<p><a href="'+hrefs[index]+'">'+addresses[index]+'</a></p>'
                      });
                      
                      google.maps.event.addListener(marker, 'click', function() {
                          if(openInfoWindow) { openInfoWindow.close(); }
                          infowindow.open(map,marker);
                          openInfoWindow = infowindow;
                      });
                  });
       				}      				
       			});
                 
             }  
         }
     } 
    function shareDD() {
        var open = false;
        $("body").click(function(event){
            if (open) {
                event.preventDefault();
                hideDD();
            }
        });
        $(window).keyup(function(event) {
            if (open && event.keyCode == 27) {
                hideDD();
            }
        });
        function hideDD() {
            open = false;
            $(".dd-share p.active").removeClass("active").next().addClass("hide");
        }
        $(".dd-share ul li a").click(function(event){
            event.stopPropagation();
        });
        $(".dd-share p").click(function(event){
            event.preventDefault();
            event.stopPropagation();
            $(this).toggleClass("active").next().toggleClass("hide");
            open = !open;
        });
    }
    function scheduleGrid() {
        if($("#filmfestival.schedule .schedulegrid").length > 0) {
			
			var h3s = "";
			var h3sLength = $("#filmfestival.schedule .schedulegrid .venue h3").length;
			var h3Height = 90;
			var budge = 119;
			//
        	$("#filmfestival.schedule .schedulegrid .venue h3").each(function(){
        	    h3s = h3s + "<h3>"+$(this).html()+"</h3>";
				$(this).remove();
        	});
        	
        	var rtl = $("html[dir='rtl']").length > 0 ? true : false;
        	
        	if (rtl) {
        	    //$('<div id="titles"></div>').appendTo("#filmfestival.schedule .schedulegrid");
        	    $('<div id="titles"></div>').insertAfter("#filmfestival.schedule .venues");
    			$("#titles").html(h3s).css({
    				position: "absolute", 
    				right: "0",
    				top: "50px", 
    				bottom: "50px", 
    				overflow: "hidden"
    			}).find("h3").css({
    				position: "static", 
    				borderBottom: "1px solid #e6e6e6"
    			}).parent().find("h3:last").css({
    				borderBottom: "0 none"
    			});
        	} else {
        	    //$('<div id="titles"></div>').appendTo("#filmfestival.schedule .schedulegrid");
        	    $('<div id="titles"></div>').insertAfter("#filmfestival.schedule .venues");
    			$("#titles").html(h3s).css({
    				position: "absolute", 
    				left: "0",
    				top: "50px", 
    				bottom: "50px",  
    				overflow: "hidden"
    			}).find("h3").css({
    				position: "static", 
    				borderBottom: "1px solid #e6e6e6"
    			}).parent().find("h3:last").css({
    				borderBottom: "0 none"
    			});
        	}
        	
        	if(rtl) {
        	    $("#filmfestival.schedule .schedulegrid .venues").css({ right: "-720px" });
        	} else {
        	    $("#filmfestival.schedule .schedulegrid .venues").css({ left: "-720px" });
        	}
			
			
			$("#filmfestival.schedule .schedulegrid").height( (h3sLength * h3Height) + budge ).schedulegrid_absolute({ 
        	    sliderContainer: $("#filmfestival.schedule .schedulegrid"), 
                sliderInner: $("#filmfestival.schedule .schedulegrid .venues"), 
                slideAmount: 360, 
                currentSet: 3, 
                budge: 0, 
                totalSlides: 5
        	});

	    }
    }
    function scrollToFBComments() {
        //
	    // Scroll to the facebook comments
	    //
	    if($(".socialbar-comments .comments").length > 0) {
	        $(".socialbar-comments .comments a").click(function(event){
	            event.preventDefault();
	            $.scrollTo("#fb-comments", 250);
	        });
	    }
	}
	function contactAutoFocus() {
	    if (!("autofocus" in document.createElement("input")) && $("#contact").length > 0) {
            $("#contact .contact input[type='text']:first").focus();
        }
	}
	function scrollToThingsToDo() {
	    $("ul.thingstodo a").click(function(event) {
	        event.preventDefault();
	        $.scrollTo(this.hash, 250);
	    });
	}
	function showFontFaceFontsFirefox() {
	    /*
	     this is called from the browser test
	     and is combined with some css
	     the idea is hide the .ff text, wait till the font loads, and then show the ff text
	     to avoid the browser FOUT
	    */
	    //$(".ff").css("visibility","hidden");
	    function showFFfonts() {
	       //$(".ff").css("visibility","visible");
	    }
	    //setTimeout(showFFfonts,2000);
	}
	function scrollToComments() {
	    $(".comments a[href^=#]").click(function(event) {
	        event.preventDefault();
	        $.scrollTo(this.hash, 250);
	    });
	}
    function scrollToBehaviour() {
        $(".scrollTo").click(function(event) {
            event.preventDefault();
            $.scrollTo(this.hash, 250);
        });
    }
    // ==================================================================
    // = Check you can obtain tickets for a film screening or an event. =
    // ==================================================================
    function checkAvailabilities(){
        
        if ($('.jsCheckAvailabilities').length > 0) {
            $('.jsCheckAvailabilities').each(function(i, screening){
                var ticketingId = $(this).attr('data-ticketing-id');
                if (ticketingId != '')  {
                    $.ajax({
                        url: '/proxy.php?action=availabilities&param=' + ticketingId,
                        success: function(data, textStatus, jqXHR) {
                            var json = data.replace('<?xml version="1.0" encoding="utf-8"?>', '');
                            json = json.replace(/<string[^>]*?>(.*)<\/string>/i, "$1");
                            var response = $.parseJSON(json);
                            var total = response[0]['total'];
                            if ( total && total >= 1 ) {
                                $(screening).addClass('hidden').siblings('.jsBookTicket').removeClass('hidden');
                                $('.jsBookTicketMessage-' + ticketingId).show(); //FIXME: It can be better :)
                            } else {
                                $(screening).addClass('hidden').siblings('.jsRushSales').removeClass('hidden');
                            }
                        },
                        error: function(data, textStatus, jqXHR) {
                            console.log('Error, the XHR result is', data);
                        }
                    });
                } else {
                    // No screening_id from datakal, so fail silently.
                    $(screening).addClass('hidden');
                }
            });
        }
    }

    // ===========================================================================
    // = Generic ToolTip widget, modeled on the calendar sidebar implementation. =
    // ===========================================================================
    function setupTooltips(){
        $('*[data-tooltip]').each(function(i, el){
            console.log('Found a tooltip', el);
            if (!isIOS) {
                $(el).mouseover(function(event) {
                    console.log('ok, shoult hover how', this);
                    var position = $(this).offset();
                    var tooltipEl = $('<p>'+ $(this).attr('data-tooltip') +'</p>');
                    tooltipEl.appendTo("body").attr("id","tooltip");
                    if ($('html[dir="ltr"]').length > 0) {
                        tooltipEl.css({ left: position.left+46, top: position.top+41});   
                    } else {
                        tooltipEl.css({ left: position.left-199, top: position.top+41});
                    }
                    tooltipEl.fadeIn(150);
                })
                .mouseout(function(event){
                    $("#tooltip").fadeOut(150, function() { $("#tooltip").remove(); });
                })
            } else {
                // Do something with a click.
            }
        })
    }
    function requestInterviewPopup() {
        $(document).ready(function(){
            $('a[data-popup-window]').each(function(){
                // If we ever upgrade jQuery, should use $(this).data('popupWindow') directly.
                $(this).popupWindow($.parseJSON($(this).attr('data-popup-window')));
            })
        })
    }
    $(document).ready(function(){
      searchBar();
      browserTest();
	      
	      
	      
        if(!isIE6) {
            $("#discover").slider({ 
        	    sliderContainer: $("#discover .discover:first"), 
                sliderInner: $("#discover .discover:first .slider"), 
                slideAmount: 756, 
                itemsVisible: 4, 
                currentSet: 1, 
                budge: 0, 
                looping: true, 
                automate: false, 
                interval: false, 
                direction: "ltr", 
                quickLinks: true
        	});

        	$("#features").slider({ 
        	    sliderContainer: $("#features:first"), 
                sliderInner: $("#features:first .slider"), 
                slideAmount: 775, 
                itemsVisible: 1, 
                currentSet: 1, 
                budge: 0, 
                looping: true, 
                automate: true, 
                interval: 4,
                direction: "ltr", 
                quickLinks: true
        	});
        	
        	var now_playing_initial = 1;
        	if ($("#mediadetail #now_playing").length > 0) {
        	    var currentVideoIndex = $("#now_playing").index("#mediadetail .slider li");
        	    var html = ""
        	    for (var i=1;i<(currentVideoIndex % 3);i++) {
                    html = html + "<li>&nbsp;</li>"
                }
                //$("#mediadetail .slider").prepend(html);
                
                
                var currentVideoIndex = $("#now_playing").index("#mediadetail .slider li");
        	    var now_playing_initial = Math.floor(currentVideoIndex / 3) + 1;
        	}

        	$("#mediadetail").slider({ 
        	    sliderContainer: $("#mediadetail .video-nav:first"), 
                sliderInner: $("#mediadetail .video-nav:first .slider"), 
                slideAmount: 255, 
                itemsVisible: 3, 
                currentSet: now_playing_initial, 
                budge: -2, 
                looping: false, 
                automate: false, 
                interval: false, 
                direction: "ttb", 
                quickLinks: false
        	});
         
         if ($(".newsletter_form")) {
            var newsletters = $('.newsletter_form');
            
            newsletters.each(function() {
              var form = $(this);
              form.submit(function() {
                $.ajax({
                  url: form.attr("action"), type: 'post',
                  data: form.serialize(),
                  success: function(data) { newsletterResults(data, form); }
                });
                return false;
              });
            })
            
          }
          
          function newsletterResults(data, element) {
            $(".success, .errors, .already_exists", element).hide();
            $("." + data, element).show();
          }

          
          if ($(".presssubscriber_form")) {
            var press = $('.presssubscriber_form');
            
            press.each(function() {
              var form = $(this);
              form.submit(function() {
                $.ajax({
                  url: form.attr("action"), type: 'post',
                  data: form.serialize(),
                  success: function(data) { pressResults(data, form); }
                });
                return false;
              });
            })
            
          }
          
          function pressResults(data, element) {
            $(".success, .errors, .already_exists", element).hide();
            $("." + data, element).show();
          }



        	listingClicks();    	
        	spotlightScroll();
        	whatsonCalendar();
        	topLink();
        	dropdownBar();
        	moreContentLinks();
        	customDD();
        	googleMaps();
        	shareDD();
        	scheduleGrid();
        	scrollToFBComments();
        	contactAutoFocus();
        	scrollToThingsToDo();
        	scrollToComments();
            scrollToBehaviour();
            checkAvailabilities();
            setupTooltips();
            requestInterviewPopup();
        	// just for development!
        	//directionSwitcher();
        }
        resizeIframe();
        submitFilm();
        defaultValues();
        alertbox();
    });
    return {
	   dropdownBar:dropdownBar, 
	   directionSwitcher: directionSwitcher
	}
}();

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function resizeIframe() {
  
  if($(".createIframe").length > 0) {
     
    $('.createIframe').each(function() {
      
      var el = $(this);
      var url = el.attr('rel');
      
      el.after('<iframe src="' + url + '" id="resizeIframe" width="536px" allowtransparency="true" scrolling="no" frameborder="0" style="background-color:#FFF; overflow:hidden"><p>Your browser does not support iframes.</p></iframe>');
      el.remove();
      
      frame = $('#resizeIframe');
      frame.height(5000);
    });

  }
}

function submitFilm() {
  
  if($('#submit_rules').length > 0) {
    
    var enabled = false;
    var checkbox = $('input[type=checkbox]', $('#submit_rules'));
    var btn = $('.btn', $('#submit_rules'));
    
    if(checkbox.length > 0) {
      
      checkbox.click(function (e) {

        if($(this).is(':checked')) {
          btn.removeClass('btn-disabled');
          enabled = true;
        }
        else {
          btn.addClass('btn-disabled');
          enabled = false;
        }
      });

      btn.click(function (e) {
        e.preventDefault();

        if(enabled) {
          $('#submit_rules').hide();
          $('#submit_content').show();

          $('#submit_content').append('<iframe src ="http://entries.dohafilminstitute.com/eng/submission.aspx" width="536px"  allowtransparency="true" height="1500px" scrolling="no" frameborder="0" id="resizedIframe" style="background-color:#FFF; overflow:hidden"><p>Your browser does not support iframes.</p></iframe>');

          $('#resizedIframe').height(2200);
          $.scrollTo(".submit-a-film", 250);
        }

      });
      
    }
  }
}

// http://jdbartlett.github.com/innershiv | WTFPL License
window.innerShiv=(function(){var d,r;return function(h,u){if(!d){d=document.createElement('div');r=document.createDocumentFragment();/*@cc_on d.style.display = 'none'@*/}var e=d.cloneNode(true);/*@cc_on document.body.appendChild(e);@*/e.innerHTML=h.replace(/^\s\s*/, '').replace(/\s\s*$/, '');/*@cc_on document.body.removeChild(e);@*/if(u===false)return e.childNodes;var f=r.cloneNode(true),i=e.childNodes.length;while(i--)f.appendChild(e.firstChild);return f}}());

