var navSlideSpeed = 500;
var searchSlideSpeed = 500;
var genericSlideSpeed = 300;
var posts;

$(document).ready(function () {
    setupForms();
    setupExpanders();
    setupOpeners();
    setupCalendar();
    setupCheckboxes();
    setupTwitterFeed();
    setupMailingForm();
    setupGallery();
    setupTennants();
    setupWorkSpaces();
    setupFacebookWall();
});

function createFBWall() {
    FB.api('114409655326070/feed', function (response) {
        if(response.data.length == 0)
		{
			$('#signedIn').append('Unfortunately it appears you are not a part of this group, please go to the group page <a href="http://www.facebook.com/groups/114409655326070/" target="_blank">here</a> and ask to join if you are a Tenant of LCB Depot or Phoenix Square, Thank you.');
		}
		else
		{
			posts = response.data;
	
			$('#signedIn').append('<ul id="wall"><form id="newMsgForm" method="post" action=""><input type="text" class="fbInput" id="newMsg" value="Share something..." /><input type="submit" class="fbSubmit" value=""/></form></ul>');
	
			$('.fbInput').focus(function () {
				if ($(this).val() == 'Share something...') {
					$(this).val('');
					$(this).css('color', '#000');
				}
			}).blur(function () {
				if ($(this).val() == 'Share something...' || $.trim($(this).val()).length == 0) {
					$(this).val('Share something...');
					$(this).css('color', '#999');
				}
			});
	
			$('.fbSubmit').click(function () {
				postNewMessage($('#newMsg').val());
				return false;
			});
	
			for (var i = 0; i < posts.length; i++) {
				var postLinks = '';
	
				for (var j = 0; j < posts[i].actions.length; j++)
					postLinks += ' &middot; <a href="' + posts[i].actions[j].link + '" class="postLink">' + posts[i].actions[j].name + '</a>';
	
				var dt = posts[i].created_time.split('T');
				var d = dt[0].split('-');
				var t = dt[1].split(':');
				var dString = d[2] + '/' + d[1] + '/' + d[0] + ' @ ' + t[0] + ':' + t[1];
	
				$('#wall').append('<li class="clearfix" userID="' + posts[i].from.id + '"><a href="" class="profilePic"><img src="http://graph.facebook.com/' + posts[i].from.id + '/picture"/></a><div class="post"><a href="" class="poster">' + posts[i].from.name + '</a><div class="postMessage">' + posts[i].message + '</div><div class="postLinks"><span class="postTime">' + dString + '</span>' + postLinks + '</div></div></li>');
	
				FB.api(posts[i].from.id, function (response2) {
					$('#wall li[userID=' + response2.id + ']').find('.poster, .profilePic').attr('href', response2.link);
				});
			}
		}
    });
}

function postNewMessage(msg) {
    FB.api('114409655326070/feed', 'post', { message: msg }, function (response) {
        if (!response || response.error) {
            alert('There was an error posting your message to the group.');
        } else {
            location.reload(true);
        }
    });
}

function setupFacebookWall() {
	if($('#fb-root').length > 0 )
	{
		FB.init({
			appId: $('input[id*=hdnAppID]').val(),
			status: true,
			cookie: true,
			xfbml: true,
			oauth: true
		});
		FB.getLoginStatus(function (response) {
			if (response.authResponse) {
				$('#facebookLogout').css('display', 'block');
				$('#signedIn').css('display', 'block');
				createFBWall();
			} else {
				$('#facebookLogin').css('display', 'block');
				$('#notSignedIn').css('display', 'block');
			}
		});
	
		$('#facebookLogin').click(function () {
			FB.login(function (response) {
				if (response.authResponse) {
					$('#facebookLogin').css('display', 'none');
					$('#facebookLogout').css('display', 'block');
					$('#notSignedIn').css('display', 'none');
					$('#signedIn').css('display', 'block');
					createFBWall();
				} else {
					alert('Login cancelled, or authorization denied.');
				}
			}, { scope: 'user_groups,publish_stream' });
		});
	
		$('#facebookLogout').click(function () {
			FB.logout(function (response) {
				$('#facebookLogout').css('display', 'none');
				$('#facebookLogin').css('display', 'block');
				$('#signedIn').css('display', 'none').empty();
				$('#notSignedIn').css('display', 'block');
			});
		});
	}
}

function setupWorkSpaces() {
    $('#workspacesOverlay, #workspacesPopout').appendTo('body');
    $('#workspacesOverlay').css('opacity',0.5);

    $('.workspacesInner > a').click(function () {
        $('.workspacesFloor').css('display', 'none');
        $($(this).attr('href')).css('display', 'block');
        $('.workspacesInner > a').removeClass('selected');
        $(this).addClass('selected');
        return false;
    });

    $('#workspacesNav > a').click(function () {
        $('.workspace').css('display', 'none');
        var e = $(this).attr('href');
        $('#workspacesNav > a').removeClass('selected');
        $(this).addClass('selected');
        $(e).css('display', 'block').children('.workspacesInner').children('a:first').trigger('click');
        return false;
    });

    $('a[href="showLCBWorkspaces"], a[href="showPhoenixWorkspaces"]').click(function () {
        $('#workspacesOverlay, #workspacesPopout').css('display', 'block');
        $('#workspacesPopout').css('top', $(window).scrollTop());
        $('#workspacesClose').click(function () {
            $('#workspacesOverlay, #workspacesPopout').css('display', 'none');
        });
        if ($(this).attr('href') == 'showLCBWorkspaces')
            $('#workspacesNav > a:first').trigger('click');
        else
            $('#workspacesNav > a:last').trigger('click');
        return false;
    });

    $('.workspaceImg').each(function () {
        if ($(this).attr('title') != undefined) {
            $(this).click(function () {
                window.location = '/tenants/' + $(this).attr('url');
            });
        }
    });

    $('.workspaceImg').hover(function () {
        var pos = $(this).offset();
        var tooltipID = $(this).attr('id');
        var tooltiptext;

        if ($(this).attr('title') != undefined)
            tooltiptext = '<strong>' + $(this).attr('name') + '</strong><br/><br/>Occupied by: ' + $(this).attr('title') + '<br/><br/>Click to view profile.';
        else
            tooltiptext = '<strong>' + $(this).attr('name');

        $('body').append('<div id="tooltip' + tooltipID + '" class="tooltip">' + tooltiptext + '<div class="tooltipbottom"></div></div>');
        $('#tooltip' + tooltipID).fadeOut(0).fadeIn(100);

        $('#tooltip' + tooltipID).css({
            'top': pos.top - $('#tooltip' + tooltipID).outerHeight() -20,
            'left': pos.left + ($(this).width() / 2) - ($('#tooltip' + tooltipID).outerWidth() / 2)
        });
    }, function () {
        $('#tooltip' + $(this).attr('id')).remove();
    });
}

function setupTennants() {
    $('#browseNav > a').click(function () {
        $(this).toggleClass('selected');
        return false;
    });

    $('.clearSearch').click(function () {
        $('#disciplinesSearchList .checkbox.checked, #locationsSearchList .checkbox.checked').removeClass('checked');
        $('#browseNav a.selected').removeClass('selected');
        doFiltering();
    });

    $('#disciplinesSearchList .checkbox, #locationsSearchList .checkbox, #browseNav a').click(function () {
        doFiltering();
    });
}

function doFiltering() {
    var disciplines = new Array();
    var buildings = new Array();
    var letterStart = new Array();

    $('#disciplinesSearchList .checkbox.checked').each(function () {
        disciplines.push($(this).children().attr('id'));
    });

    $('#locationsSearchList .checkbox.checked').each(function () {
        buildings.push($(this).children().attr('id'));
    });

    $('#browseNav .selected').each(function () {
        letterStart.push($(this).attr('href'));
    });

    if (buildings.length == 0 && disciplines.length == 0 && letterStart.length == 0)
        $('.clearSearch').hide();
    else
        $('.clearSearch').show();

    $('#tennantsList li').hide();

    $('#tennantsList li').each(function () {
        var hasDiscipline = false;
        var hasBuilding = false;
        var hasLetter = false;

        if (disciplines.length > 0) {
            for (i = 0; i < disciplines.length; i++) {
                if ($(this).attr('discipline').indexOf("[" + disciplines[i] + "]") > -1) {
                    hasDiscipline = true;
                    break;
                }
            }
        }
        else
            hasDiscipline = true;

        if (buildings.length > 0) {
            for (i = 0; i < buildings.length; i++) {
                if ($(this).attr('building').indexOf("[" + buildings[i] + "]") > -1) {
                    hasBuilding = true;
                    break;
                }
            }
        }
        else
            hasBuilding = true;

        if (letterStart.length > 0) {
            for (i = 0; i < letterStart.length; i++) {
                if ($(this).hasClass(letterStart[i])) {
                    hasLetter = true;
                    break;
                }
            }
        }
        else
            hasLetter = true;

        if (hasLetter && hasBuilding && hasDiscipline) $(this).show();
    });
}

function searchSuccess(msg) {
    $('#searchResultText, #tennantsSearch').remove();

    if (msg == 'none') {
        $('#browseNav > a.selected').removeClass('selected');
        $('#tennantsList > li').css('display', 'none');
        $('#tennantsList').before('<div id="searchResultText">No tennants found</div>');
        window.location.hash = "#searchResultText"
    }
    else
    {
        $('#browseNav > a.selected').removeClass('selected');
        $('#tennantsList > li').css('display', 'none');
        $('#tennantsList').append('<li id="tennantsSearch">' + msg + '</li>');
        $('#tennantsList').before('<div id="searchResultText">Your search returned the below results:</div>');
        window.location.hash = "#searchResultText"
    }
}

function searchFailure(msg) {
    alert('There was an error with your search, please try again. If this problem persists please contact us.');
}

function setupGallery() {
    if ($('#thumbs').length > 0) {
        var gallery = $('#thumbs').galleriffic({
            imageContainerSel: '#slideshow',
			preloadAhead: 1,
            controlsContainerSel: '#controls',
            captionContainerSel: '#caption',
            loadingContainerSel: '#loading',
            playLinkText: 'Play Slideshow',
            pauseLinkText: 'Pause Slideshow',
            prevLinkText: '&lt; Previous Photo',
            nextLinkText: 'Next Photo &gt;',
            enableTopPager: true,
            enableBottomPager: false,
            nextPageLinkText: 'Next &gt;',
            prevPageLinkText: '&lt; Prev',
            numThumbs: 8,
            maxPagesToShow: 11
        });
    }
}

function setupMailingForm() {
    $('#privacyLink').click(function () {
        $('body').append('<div id="pageOverlay"></div>');
        $('#pageOverlay').css('opacity', '0.5');
        $('#privacy-policy').css('display', 'block');
        return false;
    });

    $('#ppClose').click(function () {
        $('#pageOverlay').remove();
        $('#privacy-policy').css('display', 'none');
    });

    $('.joinmailinglist').click(function () {
        if ($(this).hasClass('open')) {
            $(this).removeClass('open');
            $('#signupForm').slideUp(genericSlideSpeed);
        }
        else {
            $(this).addClass('open');
            $('#signupForm').slideDown(genericSlideSpeed);
        }
        return false;
    });
    $('#signupForm').slideUp(0);

    $('#signupForm .formEnter').click(function () {
        var name = $('#signupName').val();
        var email = $('#signupEmail').val();
        var filter = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i

        if (name.length == 0 || email.length == 0)
            alert('Please enter both your name and email to sign up to our mailing list.');
        else if (!filter.test(email))
            alert('Please enter a valid email address to sign up to our mailing list.');
        else {
            $('#signupForm').append('<div id="signupOverlay"></div>');
            $('#signupOverlay').css('opacity', '0.6');

            CMSService.AddEmailSubscription(name, email, signupSuccess, signupFailure);
        }

        return false;
    });
}

function signupSuccess(msg) {
    if (msg == 'success') {
        $('#signupForm input').val('');
        $('#signupOverlay').remove();
        alert('You have successfully signed up to our mailing list.');
        $('#signupForm').slideUp(genericSlideSpeed, function () {
            $('.joinmailinglist').removeClass('open');
        });
    }
    else {
        $('#signupOverlay').remove();
        alert(msg);
    }
}

function signupFailure(msg) {
    alert('There was an error with your signup, please try again. If this problem persists please contact us.');
}

function setupForms() {
    $(window).keypress(function (e) {
        if (e.which == 13)
            return false;
        else
            return true;
    });
    $('.form').find('input').keydown(function (e) {
        if (e.which == 13) {
            if ($(this).parents('.form').find('.formEnter')[0].tagName.toLowerCase() == 'a')
                window.location = $(this).parents('.form').find('.formEnter').attr('href')
            $(this).parents('.form').find('.formEnter').trigger('click');
        }
    });
}

function setupTwitterFeed() {
	var timer = 0;
	$(".tweetfeed").each(function () {
	    var listname = null;
	    var tweeter = $(this).attr('tweeter');
	    var tweets = $(this).attr('tweetCount');

	    if ($(this).attr('list') != undefined)
	        listname = $(this).attr('list');

	    $(this).tweet({
	        join_text: "auto",
	        username: tweeter,
	        list: listname,
	        avatar_size: 32,
	        count: tweets,
	        auto_join_text_default: "",
	        auto_join_text_ed: "",
	        auto_join_text_ing: "",
	        auto_join_text_reply: "",
	        auto_join_text_url: "",
	        loading_text: "",
	        refresh_interval: 600,
	        template: "<div class='clearfix'><div class='tweetAvatar'>{avatar}</div><div class='tweetDetails'>{time}{join}{text}</div></div>"
	    });
	});
}

function setupCheckboxes() {
    $('.searchCB').each(function () {
        $(this).css('display', 'none').wrap('<div class="checkbox" />');
    });
    $('.checkbox').click(function () {
        if ($(this).hasClass('checked')) {
            $(this).removeClass('checked');
            $(this).children('input').removeAttr('checked');
        }
        else {
            $(this).addClass('checked');
            $(this).children('input').attr('checked', 'checked');
        }
    });
}

function setupOpeners() {
    $('.openLink').click(function () {
        if ($(this).parent().hasClass('expanded')) {
            $(this).parent().removeClass('expanded');
            $(this).parent().children('ul, div').slideUp(searchSlideSpeed);
        }
        else {
            $(this).parent().addClass('expanded');
            $(this).parent().children('ul, div').slideDown(searchSlideSpeed);
        }
        return false;
    });
}

function setupExpanders() {
    $('.expandArrow').click(function () {
        var arrow = $(this);

        if ($(this).hasClass('closed')) {
            $(this).parent().parent().children('ul').slideDown(navSlideSpeed, function () {
                $(arrow).removeClass('closed');
            });

            $(this).parent().parent().animate({
                'paddingBottom': '0'
            },
            navSlideSpeed);
        }
        else {
            $(this).parent().parent().children('ul').slideUp(navSlideSpeed, function () {
                $(arrow).addClass('closed');
            });

            $(this).parent().parent().animate({
                'paddingBottom': '25px'
            },
            navSlideSpeed);
        }
        return false;
    });
}

function setupCalendar() {
    $('#datepicker').datepicker({
        dayNamesMin: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
        firstDay: 1,
        prevText: '',
        nextText: '',
        beforeShowDay: function (date) {
            var result = [true, '', ''];

            for (var i = 0; i < dates.length; i++) {
                if (date.valueOf() == dates[i][0].valueOf()) {
                    result = [true, 'event', dates[i][1]];
                    break;
                }
            }

            return result;
        },
        onSelect: function (dateText, inst) {
            var d = dateText.split("/");
            var temp = d[0];
            d[0] = d[1];
            d[1] = temp;
            window.location = "/events/" + d.join("-");
        },
        onChangeMonthYear: function (year, month, inst) {
            setTimeout("updateCalendarTooltips();", 200);
        }
    });
    updateCalendarTooltips();
}

function updateCalendarTooltips() {
    var i = 0;
    $('.ui-datepicker-calendar td').each(function () {
        if ($(this).hasClass('ui-datepicker-week-end'))
            $(this).attr('title', '').removeClass('event');

        if ($(this).attr('title') != undefined) {
            if ($(this).attr('title').length > 0) {
                $(this).attr('tooltip-text', $(this).attr('title')).attr('tooltipID', i + 1).removeAttr('title');
                i++;

                $(this).hover(function () {
                    var pos = $(this).offset();
                    var tooltipID = $(this).attr('tooltipID');

                    $('body').append('<div id="tooltip' + tooltipID + '" class="tooltip">' + $(this).attr('tooltip-text') + '<div class="tooltipbottom"></div></div>');
                    $('#tooltip' + tooltipID).fadeOut(0).fadeIn(100);

                    $('#tooltip' + tooltipID).css({
                        'top': pos.top - $('#tooltip' + tooltipID).outerHeight() - 20,
                        'left': pos.left - ($('#tooltip' + tooltipID).outerWidth() / 2) + 13
                    });
                }, function () {
                    $('#tooltip' + $(this).attr('tooltipID')).remove();
                });
            }
        }
    });
}
