var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $(this).find('ul').css('display', 'block');
}

function jsddm_close() {
    if(ddmenuitem) ddmenuitem.css('display', 'none');
}

function jsddm_timer() {
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
    if(closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

$(document).ready(function() {
    $('#jsddm > li').bind('mouseover', jsddm_open);
    $('#jsddm > li').bind('mouseout',  jsddm_timer);
});

document.onclick = jsddm_close;


$(document).ready(function() {
	check_logged_state();
    if (showlogin == true) {
        $("#headerLoginDiv").show();
    }
    if (typeof(newsblock) != 'undefined') {
        $('#dotnews1').bind('click', "1", switch_news);
        $('#dotnews2').bind('click', "2", switch_news);
        $('#dotnews3').bind('click', "3", switch_news);
        $('#dotnews4').bind('click', "4", switch_news);
    }
    if (typeof(related) != 'undefined') {
        $('#dot1').bind('click', "1", switch_related);
        $('#dot2').bind('click', "2", switch_related);
        $('#dot3').bind('click', "3", switch_related);
        $('#dot4').bind('click', "4", switch_related);
    }
    $(".loginButton").click(function () {
        if ($("#headerLoginDiv").is(":hidden")) {
            $("#headerLoginDiv").slideDown("normal");
        } else {
            $("#headerLoginDiv").slideUp("normal");
        }
    });
    $("a#notlogged_in").bind("click", scrolltologin);
    $('#newsletter').bind("focus", [$('#newsletter'), "EMAIL ADDRESS"], focus_input);
    $('#newsletter').bind("blur", [$('#newsletter'), "EMAIL ADDRESS"], blur_input);
    $('#add_email').bind("click", join_newsletter);
	if (typeof(prettyphoto) != 'undefined') {
		$("a[rel^='prettyPhoto']").prettyPhoto({
		animationSpeed: 'normal', /* fast/slow/normal */
		showTitle: true, /* true/false */
		allowresize: true, /* true/false */
		counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
		theme: 'facebook' /* light_rounded / dark_rounded / light_square / dark_square / facebook */
		});
	}
    if (typeof(artistlist) != 'undefined') {
        $('#subSearch').bind("focus", [$('#subSearch'), "SEARCH ARTISTS..."], focus_input);
        $('#subSearch').bind("blur", [$('#subSearch'), "SEARCH ARTISTS..."], blur_input);
        
        $('#subSearch').bind('keypress', function(e) {
                if(e.keyCode==13){
                    search_artist("search");
                }
        });

        $(".mediaOptionsBarSort").click(function () {
          if ($(".sortArtistsDiv").is(":hidden")) {
            $(".sortArtistsDiv").slideDown("normal");
          } else {
            $(".sortArtistsDiv").slideUp("normal");
          }
        });
    }
    if (typeof(commentlist) != 'undefined') {
        $('#add_post').bind("click", submit_post);
    }
    if (typeof(calendar) != 'undefined') {
        $(".tooltip-target").ezpz_tooltip();
        $('#prev_year').bind("click", [previous_year], view);
        $('#prev_month').bind("click", [previous_month], view);
        $('#next_month').bind("click", [next_month], view);
        $('#next_year').bind("click", [next_year], view);
    }
    if (typeof(videolist) != 'undefined') {
        $('#videosearch').bind("focus", [$('#videosearch'), "SEARCH VIDEOS..."], focus_input);
		$('#videosearch').bind("blur", [$('#videosearch'), "SEARCH VIDEOS..."], blur_input);
    }
    if (typeof(video) != 'undefined') {
        $(".carouselScroller").jCarouselLite({
			btnNext: ".next",
			btnPrev: ".prev",
			beforeStart: function(a) {
				var offset = $("#carouseloffset").val();
				
				urlsegment = path + "tv/get_next";
				$.ajax({
					url     : urlsegment,
					type    : "post",
					timeout : 20000,
					data    : ({offset : offset}),
					dataType: "json",
					error   : function(XMLHttpRequest, textStatus, errorThrown) {
								//alert("An error has occurred, please try again later");
								//$('#loading_videos').hide();
								//$('#allVideoThumbsHolder').show();    
							  },
					success : function(response) {
								var id1 = parseInt(offset) + 1;
								var id2 = parseInt(offset) + 2;
								var id3 = parseInt(offset) + 3;
								var id4 = parseInt(offset) + 4;
								$("#carouselImage" + id1).html(response.imageone);
								$("#carouselImage" + id2).html(response.imagetwo);
								$("#carouselImage" + id3).html(response.imagethree);
								$("#carouselImage" + id4).html(response.imagefour);
								
								$("#carouselText" + id1).html(response.titleone);
								$("#carouselText" + id2).html(response.titletwo);
								$("#carouselText" + id3).html(response.titlethree);
								$("#carouselText" + id4).html(response.titlefour);
								
								$("#carousellink" + id1).attr("href", response.linkone);
								$("#carousellink" + id2).attr("href", response.linktwo);
								$("#carousellink" + id3).attr("href", response.linkthree);
								$("#carousellink" + id4).attr("href", response.linkfour);
								
								$("#carouseloffset").val(id4);
							}
				});
			},
			circular: false,
			visible: 4,
			scroll: 4
		});
    }
});

function scrolltologin () {
    $.scrollTo('#loginscrollto', 1600, {onAfter:function(){
            $("#headerLoginDiv").slideDown("normal");
        }
    })
}

function display_login() {
    if ($("#headerLoginDiv").is(":hidden")) {
        $("#headerLoginDiv").slideDown("normal");
    } else {
        $("#headerLoginDiv").slideUp("normal");
    }
}

function join_newsletter() {
    var email = $('#newsletter').val();
    
    $('#sideBarJoinNewsletterHolder').hide();    
    $('#newsletter_loading').show();
            
    urlsegment = path + "user/add_email";
    $.ajax({
        url     : urlsegment,
        type    : "post",
        timeout : 20000,
        data    : ({email : email}),
        dataType: "json",
        error   : function(XMLHttpRequest, textStatus, errorThrown) {
                    //alert("An error has occurred, please try again later");
                    $('#newsletter_loading').hide();
                    $('#sideBarJoinNewsletterHolder').show();    
                  },
        success : function(response) {
                    var str = response.str;
                    
                    $('#sideBarJoinNewsletterHolder').html(str);
                    $('#newsletter_loading').hide();
                    $('#sideBarJoinNewsletterHolder').fadeIn('slow');
                }
    });
    return true;
}

function check_logged_state() {
    urlsegment = path + "user/get_logged_state";
    $.ajax({
        url     : urlsegment,
        type    : "post",
        timeout : 20000,
        data    : ({}),
        dataType: "json",
        error   : function(XMLHttpRequest, textStatus, errorThrown) {
                    //alert("An error has occurred, please try again later");  
                  },
        success : function(response) {
					//if (response.showsurvey == true) {
					//	$.prettyPhoto.open('#surveyPopUp','Survey');
					//}
			
					var logged_in = response.logged_in;
					var fbookuser = response.fbookuser;
					var str = "";
                    if (logged_in == false) { 
                        str += '<div class="headerJoinAssembly">' +
                            '<img src="' + path + 'images/join_assembly.png" alt="JOIN ASSEMBLY" />' +
                        '</div>' +
						'<div class="headerWhatsForYou">' +
                            '<a href="' + path + 'venue/online">' +
                                'WHAT\'S IN IT FOR YOU?' +
                            '</a>' +
                        '</div>';
                    } else {
                        str += '&nbsp;&nbsp;';
                    }
					if (logged_in == true) {
                        str += '<div class="loggedInDiv">';
                        if (fbookuser == true) {
							var username = response.username;
							str += 'HI <span class="nameColour">' + username.toUpperCase() + '&nbsp;&nbsp;</span>' +
							'<span class="editLinks">(<a href="' + path + 'user/edit_fbuser" >EDIT PROFILE</a>/<a href="' + path + '" onclick=\'FB.Connect.logout(function() { window.location="' + path + '" }); return false;\' >LOGOUT)</a></span>';
						} else {
							var username = response.username;
							str += 'HI <span class="nameColour">' + username.toUpperCase() + '</span>&nbsp;&nbsp;' +
							'<span class="editLinks">(<a href="' + path + 'user/edit_user" >EDIT PROFILE</a>/<a href="' + path + 'user/logout" >LOGOUT)</a></span>';
						} 
                        str += '</div>' +
                        '<div class="loggedInPic">';
                            if (fbookuser == true) {
							var pic_square = response.pic_square;
                            str += '<img class="profile_square" src="' + pic_square + '" width="32" height="26" />';
                            } else { 
                            str += '<img src="' + path + 'images/user/mini_thumb_' + response.userimage + '" width="32" height="26" />';
                            } 
                        str += '</div>';
                    } else { 
                        str += '<div class="headerSignup">' +
                            '<a href="' + path + 'user/signup">' +
                                '<img src="' + path + 'images/signup.png" alt="SIGNUP" />' +
                            '</a>' +
                        '</div>' +
                        '<div class="headerOr">' +
                            'or' +
                        '</div>' +
                        '<div class="headerLogin">' +
                            '<img src="' + path + 'images/login.png" alt="LOGIN" class="loginButton" />' +
                        '</div>';
                    }
                    if (logged_in == false) {
						var fullpath = document.URL;
						var fullpath = fullpath.replace(/\//g, "+");
                        str += '<div class="headerFacebookLogin">' +
                            '<fb:login-button onlogin=\'window.location="' + path + 'user/login_fb_user/' + fullpath + '\' size="medium"></fb:login-button>' +
                        '</div>';
                    }
                    str += '<br clear="all" />';
					$("#headerLoginHolder").html(str);
					
					$(".loginButton").click(function () {
						if ($("#headerLoginDiv").is(":hidden")) {
							$("#headerLoginDiv").slideDown("normal");
						} else {
							$("#headerLoginDiv").slideUp("normal");
						}
					});
					FB.init("c03685db2fafbf6ad8bd2681275f8a42", "/xd_receiver.htm");
                }
    });
    return true;
}
