﻿var textChanged = false;
var loginObject = new Object();
loginObject.LoginName = false;
loginObject.AfterLogin = null;

$(window).load(function() {

resizeAllImages();
$('body').ajaxComplete(function() { resizeAllImages() });
});
$(document).ready(function() {
    $.get('/Account/GetLogin', function(data) {
        loginObject.LoginName = data;
    });

    linkSchoolSearch();


    //$('.tweet-picture').each(function() {
    //    $(this).toggle(function() { resizeImage($(this), 500, 330); }, function() { resizeImage($(this), 145, 95); });

    //});
    $('#main-menu-holder').dropDownMenu({ timer: 50, numberOfLevels: 2, parentMO: 'parent-hover', childMO: 'child-hover1' });
    preloadImages(['/Content/Images/dropdown_menu.png']);
});

function resizeAllImages() {
    $('.tweet-picture-thumbnail').each(function() { resizeImage($(this), 145) });
    $('.tweet-picture-full').each(function() { resizeImage($(this), 500) });
}
function setupJoinPage() {
    $('#choose-schools-add-school-link').click(function() {
        $('#choose-schools-add-school').show();
        $('#choose-schools-add-school-link').hide();
        $('#choose-schools-link-divider').hide();
    });
    $('#choose-schools-second-school-link').click(function() {
        $('#choose-schools-school2').show();
        $('#use-second-school').val('true');
        $('#choose-schools-second-school-link').hide();
        $('#choose-schools-link-divider').hide();
    });
    $('#choose-schools-check-school').click(function() {
        $('#choose-schools-ajax-loader-holder').show();
        $.getJSON('/Join/CheckSchool', { url: $('#choose-schools-add-school-website').val() }, function(data) {
            $('#choose-schools-ajax-loader-holder').hide();
            if (data.valid == true) {
                $('#choose-schools-add-school-error').hide();
                $('#choose-schools-add-school-submit-section').show();
            }
            else {
                $('#choose-schools-add-school-error').text(data.reason);
                $('#choose-schools-add-school-error').show();
            }
        });
    });

    $('#choose-schools-add-school-button').click(function() {
        $('#choose-schools-ajax-loader-holder').show();
        $('#choose-schools-add-school-button').attr('disabled', 'true');
        $.getJSON('/Join/CheckSchool', { url: $('#choose-schools-add-school-website').val() }, function(data) {
            $('#choose-schools-ajax-loader-holder').hide();
            if (data.valid == true) {
                $('#choose-schools-ajax-loader-holder').show();
                $.post('/Join/AddSchool', { url: $('#choose-schools-add-school-website').val(), state: $('#new-school-state').val() },
                function() {
                    $('#choose-schools-ajax-loader-holder').hide();
                    $('#choose-schools-add-school').hide();
                    $('#state1').val($('#new-school-state').val());
                    $('#state1').change();
                });
            }
            else {

            }
        });
    });

    $('#state1').change(function() {
        $('#choose-schools-ajax-loader-holder').show();
        $.get('/Join/ListSchools', { state: $('#state1').val() }, function(data) {
            $('#choose-schools-ajax-loader-holder').hide();
            $('#school1').empty();
            $('#school1').append(data);

        });
    });
    $('#school1').change(function() {
        if (!textChanged)
            $('#choose-schools-tweet-message').text("Just added myself to http://campustweet.com - " + $('#school1 option:selected').text());
    });
    $('#school2').change(function() {
        if (!textChanged)
            $('#choose-schools-tweet-message').text("Just added myself to http://campustweet.com - " + $('#school1 option:selected').text() + " and " + $('#school2 option:selected').text());
    });
    $('#state2').change(function() {
        $('#choose-schools-ajax-loader-holder').show();
        $.get('/Join/ListSchools', { state: $('#state2').val() }, function(data) {
            $('#choose-schools-ajax-loader-holder').hide();
            $('#school2').empty();
            $('#school2').append(data);

        });
    });
    $('#choose-schools-ajax-loader-holder').show();
    $.get('/Join/ListStates', function(data) {
        $('#choose-schools-ajax-loader-holder').hide();
        $('#state1').append(data);
        $('#state2').append(data);
        $('#new-school-state').append(data);
        $('#state1').change();
        $('#state2').change();

    });
}

function limitText(selector, counter, maxChars) {
    $(selector).keydown(function() {
        textChanged = true;
        if ($(selector).val().length > maxChars) {
            $(selector).val($(selector).val().substring(0, maxChars));
            return false;
        }
        else {
            $(counter).text(maxChars - $(selector).val().length);
        }
    });
    $(selector).keyup(function() {
        textChanged = true;
        if ($(selector).val().length > maxChars) {
            $(selector).val($(selector).val().substring(0, maxChars));
            return false;
        }
        else {
            $(counter).text(maxChars - $(selector).val().length);
        }
    });
}

function limitText2(selector, counter, maxChars) {
    if ($(selector).val().length > maxChars) {
        $(selector).val($(selector).val().substring(0, maxChars));
        return false;
    }
    else {
        $(counter).text(maxChars - $(selector).val().length);
    }
}
function linkSchoolSearch() {
    $(".school-search").autocomplete('/Schools/Search', { matchContains: true, mustMatch: true, scroll: true });
    $(".school-search").result(function(event, data, formatted) {
        //$("#school-search-id").val(data[1]);
        window.location = '/Schools/' + data[1];
    });
}
function linkSchoolLetters() {
    $('.all-schools-letter').bind('click', getSchoolsByLetter);
}
function linkSchoolStates() {

    $('.all-schools-state').bind('click', getSchoolsByState);
    $('.all-schools-header-back').bind('click', showStates);
}
function getSchoolsByState() {
    $('#all-schools-states-container').hide();
    $('#all-schools-states-schools-container').show();
    $('#all-schools-states-schools-container').empty();
    $('#all-schools-states-schools-container').addClass('loading-image');
    $('.all-schools-header-state-state').text($(this).text());
    $('.all-schools-header-state-state').show();
    $('.all-schools-header-back').show();
    $.get('/Schools/SchoolsByState', { state: $(this).text() }, function(data) {
        $('#all-schools-states-schools-container').removeClass('loading-image');
        $('#all-schools-states-schools-container').append(data);
    });
}
function getSchoolsByLetter() {
    $('#all-schools-alphabet-container').empty();
    $('#all-schools-alphabet-container').addClass('loading-image');
    $.get('/Schools/SchoolsByLetter', { letter: $(this).text() }, function(data) {
        $('#all-schools-alphabet-container').removeClass('loading-image');
        $('#all-schools-alphabet-container').append(data);
    });
}
function showStates() {
    $('#all-schools-states-schools-container').hide();
    $('.all-schools-header-state-state').hide();
    $('.all-schools-header-back').hide();
    $('#all-schools-states-container').show();

}

function linkPeopleLetters() {
    $('.all-people-letter').bind('click', getPeopleByLetter);
}

function getPeopleByLetter() {
    $('#all-people-alphabet-container').empty();
    $('#all-people-alphabet-container').addClass('loading-image');
    $.get('/People/PeopleByLetter', { letter: $(this).text() }, function(data) {
        $('#all-people-alphabet-container').removeClass('loading-image');
        $('#all-people-alphabet-container').append(data);
    });
}

function initializeMoreTweetsLink() {
    $('#school-details-tweet-more-link').click(function() {
        $('#school-details-tweet-more-link').hide();
        $('#school-details-tweet-more-loader').show();
        $.getJSON('/Schools/MoreTweets', { timeStamp: $('#school-details-tweet-timestamp').val(),
            schoolID: $('#school-details-tweet-campus').val()
        }, function(data) {
            $('#school-details-tweet-more-loader').hide();
            $('#school-details-tweet-more-link').show();
            $('#school-details-tweet-timestamp').val(data.timeStamp);
            $('#school-details-tweets-list').append(data.tweets);
        });
    });
}

function inspectObject(obj) {
    for (var member in obj) {
        if (!obj.hasOwnProperty(member) || typeof (obj[member]) === "function") continue;
        alert(member + ': ' + obj[member]);
    }
}

var imagesAttempts = 0;
var imagesLoading = null;
var imagesRunning = false;
function checkImages(selector, callback, params) {

    if (imagesRunning === true) { return; }
    imagesRunning = true;
    
	var unloaded = 0;
	$(selector).each(function(i, val) {
	    if (val.complete === false) {
	        unloaded++;
	    }
	});
	
	var isLoaded = (unloaded === 0);
	if(imagesLoading !== null)
	{
		imagesAttempts++;
		if(isLoaded || imagesAttempts > 100)
		{
			// Stop the image load check
			clearInterval(imagesLoading);
			imagesLoading = null;
			
			// Call the post function
			if (typeof callback == 'function') {
			    callback(params);
			}
		}
	}

	imagesRunning = false;
	return isLoaded;
}

function waitImages(selector, callback, params) {
    imagesAttempts = 0;
    imagesLoading = setInterval(function() {
        checkImages(selector, callback, params);
    }, 100);
}

	
function activateMorePaging(prefix, url) {
    var link = $('#' + prefix + '-more-link');
    var more = $('#' + prefix + '-more-loader');

    link.click(function() {
        var page = parseInt($('#' + prefix + '-page').val()) + 1;
        var id = parseInt($('#' + prefix + '-id').val());
        
        link.hide();
        more.show();
        
        $.getJSON(url, { page: page, mainID: id }, function(data) {
            more.hide();
            link.show();

            $('#' + prefix + '-page').val(page);
            $('#' + prefix + '-list').append(data.result);
        });
    });
}


function finishPaging(params) {
    jQuery.each(params[0], function(i, val) {
        val.show();
    });

    jQuery.each(params[1], function(i, val) {
        val.hide();
    });
}

function updatePaging(prefix, url, direction, wait) {
    var maxPage = parseInt($('#' + prefix + '-maxPage').val());
    var page = parseInt($('#' + prefix + '-page').val()) + direction;
    var id = parseInt($('#' + prefix + '-id').val());

    var list = $('#' + prefix + '-list');
    var prev = $('#' + prefix + '-prev-link');
    var next = $('#' + prefix + '-next-link');
    var more = $('#' + prefix + '-more-loader');

    prev.hide();
    next.hide();
    more.show();

    $.getJSON(url, { page: page, mainID: id }, function(data) {
        $('#' + prefix + '-page').val(page);
        if (data.max && data.max === true) {
            maxPage = page;
            $('#' + prefix + '-maxPage').val(maxPage);
        }

        var show = [];
        var hide = [];

        hide.push(more);
        if (page != 1) { show.push(prev); }
        if (page != maxPage) { show.push(next); }

        if (wait === true) {
            list.hide();
            show.push(list);
        }

        list.html(data.result);

        if (wait === true) {
            waitImages('#' + prefix + '-list img', finishPaging, [show, hide]);
        } else {
            finishPaging([show, hide]);
        }
    });
}

function activatePaging(prefix, url, wait) {
    var maxPage = parseInt($('#' + prefix + '-maxPage').val());
    
    $('#' + prefix + '-prev-link').click(function() {
        updatePaging(prefix, url, -1, wait);
    });

    $('#' + prefix + '-next-link').click(function() {
        updatePaging(prefix, url, 1, wait);
    });

    if (maxPage == 1)
        $('#' + prefix + '-next-link').hide();

    // Make sure the page starts out at 1 (form elements don't refresh)
    $('#' + prefix + '-page').val(1);
}

var schoolDetailsHistorySelect = false;
function schoolDetailsTabSelect(event, ui) {
    if (schoolDetailsHistorySelect !== true) {
        document.location.hash = (ui.tab.hash.split('_'))[0];
    }
    return true;
}
function schoolDetailsPageLoad(hash) {
    schoolDetailsHistorySelect = true;
    $("#school-details-content").tabs('select', hash + '_tab');
    schoolDetailsHistorySelect = false;
}
var peopleDetailsHistorySelect = false;
function peopleDetailsTabSelect(event, ui) {
    if (peopleDetailsHistorySelect !== true) {
        document.location.hash = (ui.tab.hash.split('_'))[0];
    }
    return true;
}
function peopleDetailsPageLoad(hash) {
    peopleDetailsHistorySelect = true;
    $("#person-details-tweets-holder").tabs('select', hash + '_tab');
    peopleDetailsHistorySelect = false;
}

function peopleDetailsMoreTweets() {
    $('#person-details-tweets-tweets-more-link').click(function() {
        $('#person-details-tweets-tweets-more-link').hide();
        $('#person-details-tweets-tweets-more-loader').show();
        $.getJSON('/People/MoreTweets', { personID: $('#person-details-person-id').val(),
            tweetID: $('#person-details-tweets-last-id').val()
        }, function(data) {
            $('#person-details-tweets-tweets-more-loader').hide();
            $('#person-details-tweets-tweets-more-link').show();
            $('#person-details-tweets-last-id').val(data.newID);
            $('#person-details-tweets-tweets-holder-inner').append(data.text);
        });


    });
}
function peopleDetailsMoreConversations() {
    $('#person-details-tweets-conversations-more-link').click(function() {
    $('#person-details-tweets-conversations-more-link').hide();
    $('#person-details-tweets-conversations-more-loader').show();
        $.getJSON('/People/MoreConversations', { personID: $('#person-details-person-id').val(),
        count: $('#person-details-tweets-conversations-count').val()
        }, function(data) {
            $('#person-details-tweets-conversations-more-loader').hide();
            $('#person-details-tweets-conversations-more-link').show();
            $('#person-details-tweets-conversations-count').val(data.newCount);
            $('#person-details-tweets-conversations-holder-inner').append(data.text);
        });


    });
}

function showLogonWindow() {
    var w = window.open('/Account/Logon', 'popup', 'width=800,height=400,resize=no,scrollbar=no');
    w.focus();
}

function checkLogon(username) {
    if ($('#success-indicator').val() == "True") {
        if (window.opener != null) {
            window.opener.afterLogin(username);
        }

    }
    else {
        window.opener.failedLogon();
    }
    self.close();
}
function confirmLogon() {
    if ($('#return-url').val() != null)
        window.location = $('#return-url').val();
}

function failedLogon() {

}

function showReplyOption(id) {

    $('#tweet-retweet-' + id).hide();
    $('#tweet-reply-' + id + '-comments').val('@' + $('#tweet-name-' + id).text() + ' ');

    $('#tweet-reply-' + id).fadeIn(1000);
    $('#tweet-reply-' + id).focus();
    //have to call it twice - bug in jquery?
    $('#tweet-reply-' + id + '-comments').trigger('keyup');
    $('#tweet-reply-' + id + '-comments').trigger('keyup');
}
function showRetweetOption(id) {


    $('#tweet-reply-' + id).hide();
    $('#tweet-retweet-' + id + '-comments').val('RT @' + $('#tweet-name-' + id).text() + $('#tweet-text-' + id).text());

    $('#tweet-retweet-' + id).fadeIn(1000);
    $('#tweet-retweet-' + id).focus();
    $('#tweet-retweet-' + id + '-comments').trigger('keyup');
    $('#tweet-retweet-' + id + '-comments').trigger('keyup');
}

function cancelReply(id) {
    $('#tweet-reply-' + id + '-comments').val('');
    $('#tweet-reply-' + id).hide();
}
function cancelRetweet(id) {
    $('#tweet-retweet-' + id + '-comments').val('');
    $('#tweet-retweet-' + id).hide();
}
function submitReply(id) {
    if (loginObject.LoginName === null) return false;
    $('#tweet-comments-' + id + '-loading-image').show();
    $('#tweet-comments-' + id + '-status-text').text('');
    $('#tweet-comments-' + id + '-status-holder').fadeIn(500);
    if (loginObject.LoginName == '') {
        $('#tweet-comments-' + id + '-loading-image').hide();
        $('#tweet-comments-' + id + '-status-holder').hide();
        loginObject.AfterLogin = function() { submitReply(id) };
        var w = window.open('/Account/Logon', 'login', 'width=800,height=400,resize=no,scrollbar=no');
        return true;
    }
    else {
        $('#tweet-reply-' + id).hide();
        $.post('/Account/UpdateStatus', { comments: $('#tweet-reply-' + id + '-comments').val(), replyToID: id }, function(data) {
            $('#tweet-comments-' + id + '-loading-image').hide();
            if (data == 'True') {
                $('#tweet-comments-' + id + '-status-text').text('Your update was successfully posted.');
            }
            else {
                $('#tweet-comments-' + id + '-status-text').text('Your update failed!.');
            }
            $('#tweet-comments-' + id + '-status-holder').fadeOut(4000);
        });

    }
}
function submitRetweet(id) {
    if (loginObject.LoginName === null) return false;
    $('#tweet-comments-' + id + '-loading-image').show();
    $('#tweet-comments-' + id + '-status-text').text('');
    $('#tweet-comments-' + id + '-status-holder').fadeIn(500);
    if (loginObject.LoginName == '') {
        $('#tweet-comments-' + id + '-loading-image').hide();
        $('#tweet-comments-' + id + '-status-holder').hide();
        loginObject.AfterLogin = function() { submitRetweet(id) };
        var w = window.open('/Account/Logon', 'login', 'width=800,height=400,resize=no,scrollbar=no');

        return true;

    }

    else {
        $('#tweet-retweet-' + id).hide();
        $.post('/Account/UpdateStatus', { comments: $('#tweet-retweet-' + id + '-comments').val() }, function(data) {
            $('#tweet-comments-' + id + '-loading-image').hide();
            if (data == 'True') {
                $('#tweet-comments-' + id + '-status-text').text('Your update was successfully posted.');
            }
            else {
                $('#tweet-comments-' + id + '-status-text').text('Your update failed!.');
            }
            $('#tweet-comments-' + id + '-status-holder').fadeOut(4000);



        });
    }
}

function afterLogin(username) {
    loginObject.LoginName = username;
    if (loginObject.AfterLogin !== undefined)
        loginObject.AfterLogin();
    loginObject.AfterLogin = null;
}

function preloadImages(imageArray)
{
	if(document.images)
	{
		var numNewImages = imageArray.length;
		if(!document.imagePreload) {
			document.imagePreload = []; }
		var numImages = document.imagePreload.length;
		for(var preloadNum = numImages; preloadNum < numImages + numNewImages; ++preloadNum) {
		    document.imagePreload[preloadNum] = new Image;
			document.imagePreload[preloadNum].src = imageArray[preloadNum - numImages];
		}
	}
}

function showHide(elementToShow, elementToHide) {
    $(elementToHide).hide();
    $(elementToShow).show();
}

function showHideWithFade(elementToShow, elementToHide, fadeTime) {
    $(elementToHide).hide();
    $(elementToShow).fadeIn(fadeTime);
}

function getPeopleByName(elementToFill, indicatorElement, letter) {
    $(elementToFill).empty();
    $(indicatorElement).show();
    $.get('/People/PeopleByName', { letter: letter }, function(data) {
        $(indicatorElement).hide();

        $(elementToFill).append(data);
    });
}
function getPeopleByScreenName(elementToFill, indicatorElement, letter) {
    $(elementToFill).empty();
    $(indicatorElement).show();
    $.get('/People/PeopleByScreenName', { letter: letter }, function(data) {
        $(indicatorElement).hide();

        $(elementToFill).append(data);
    });
}

function getSchoolsByName(elementToFill, indicatorElement, letter) {
    $(elementToFill).empty();
    $(indicatorElement).show();
    $.get('/Schools/SchoolsByName', { letter: letter }, function(data) {
        $(indicatorElement).hide();

        $(elementToFill).append(data);
    });
}
function getSchoolsByState(elementToFill, indicatorElement, state) {
    $(elementToFill).empty();
    $(indicatorElement).show();
    $.get('/Schools/SchoolsByState', { state: state }, function(data) {
        $(indicatorElement).hide();

        $(elementToFill).append(data);
    });
}


function resizeImage(selector, maxDimension) {
    
    var originalWidth = selector.width();
    var originalHeight = selector.height();
    var height;
    var width;
    if (originalWidth > originalHeight) {
        
        height = (maxDimension / originalWidth) * originalHeight;
        width = maxDimension;

    }
    else {
        width = (maxDimension / originalHeight) * originalWidth;
        height = maxDimension;

    }
    selector.height(height);
    selector.width(width);
    selector.css('display', 'block');
}