/// <reference path="jquery.intellisense.js" />

var mosaicState;
var searchState;
var $j = jQuery;

//Onload event. Leverages jQuery.
$j (document).ready(function() {
    toolTipListener();
    getMosaicGrid();
    addPhotoRadioListener();

    mosaicSearchListener();

    //New window listener
    $j ('a[rel="external"]').newWindow();

    //Popup listeners
    $j ('a.legal-pop').popup();

    storyFieldListener();
});


function addPhotoRadioListener() {
    $j (".include-yes input").click(function(event) {
        addPhotoRadioCallback();
    });
    $j (".include-no input").click(function(event) {
        addPhotoRadioCallback();
    });
    addPhotoRadioCallback();
}

function addPhotoRadioCallback(radioClicked) {
    if ($j (".include-yes input").length == 0) return false;
    if ($j (".include-yes input:checked").length > 0) {
        $j (".groupfield").slideDown();
    }
    else if ($j (".include-no input:checked").length > 0) {
        $j (".groupfield").slideUp();
    }
}

function mosaicSearchListener()
{
    if ($j ("#mosiac-interact").length == 0) return false;

    $j (window).keydown(function(e) {
        if (e.which == 13) {
            $j ('#mosaic-error').html('You must click one of the "Go" buttons to activate a mosaic search.').show();
        }
    });

    $j ("#activate-group-search").click(function(event) {
    searchMosaic("group");
    });
    
    $j ("#activate-name-search").click(function(event) {
    searchMosaic("name");
    });
}

function searchMosaic(whichSearch) {
    $j (".highlight").each(function(e) {
        $j (this).remove();
    });
    
    if (whichSearch == "group") {
        var searchString = $j ("#searchGroupName").val();
        $j ("#searchName").val("");
        var gridObjects = CatChowPink.Web.WebUtility.GetGroupNameGrid(searchString);
    }
    else {
        var searchString = $j ("#searchName").val();
        $j ("#searchGroupName").val("");
        var gridObjects = CatChowPink.Web.WebUtility.GetSearchGrid(searchString);
    }

    if (gridObjects.value == null) {
        drawErrorResults("too many results");
    }
    else if (gridObjects.value == 0) {
        drawErrorResults("no results");
    }
    else {
        var tiles = gridObjects.value;
        var position = 0;

        searchState = new Array(115);
        for (var y = 0; y < 115; y++) {
            searchState[y] = new Array(87);
            for (var x = 0; x < 87; x++) {
                searchState[y][x] = {};
                if (tiles[position] != 0) {
                    searchState[y][x].hasPhoto = true;
                } else {
                    searchState[y][x].hasPhoto = false;
                }
                searchState[y][x].left = x * 10;
                searchState[y][x].top = y * 10;
                searchState[y][x].photoPosition = tiles[position];
                position = position + 1;
            }
        }
        drawSearchResults();
    }
}

function drawSearchResults() {
    if ($j ("#mosiac-interact").length == 0) return false;
    $j ('#mosaic-error').hide();
    for (var y = 0; y < 115; y++) {
        for (var x = 0; x < 87; x++) {
            var tile = searchState[y][x];
            if (tile.hasPhoto == true) {
                $j ("<div class='highlight'></div>").css("top", tile.top).css("left", tile.left).appendTo("#mosiac-interact");
            }
        }
    }
    $j ('#search-results').show();
}

function drawErrorResults(errorStatus) {
    if (errorStatus == "too many results") {
        $j ('#mosaic-error').html('Sorry, your search returned too many results. Please narrow your search terms.').show();
    }
    else if (errorStatus == "no results") {
        $j ('#mosaic-error').html('Sorry, your search returned no results. Please try again.').show();
    }
    $j ('#search-results').hide();
}

function mosaicListener()
{
    $j ('#mosiac-interact').bind("mouseenter", function(e) {
        mosaicSubListener();
    });

    $j ('#mosiac-interact').bind("mouseleave", function(e) {
        $j ("#active-tile").hide();
        $j ("#tooltip").hide();
        $j ("#tooltip-pointer").hide();
        $j ('#mosiac-interact').unbind("mousemove");
        inputDelayer();
    });

    activeTileListener();
}

function delayTimer(delay) {
    var timer;
    return function(fn) {
        timer = clearTimeout(timer);
        if (fn)
            timer = setTimeout(function() {
                fn();
            }, delay);
        return timer;
    }
}

var tile = "";
function mosaicSubListener() {
    $j ('#mosiac-interact').bind("mousemove", function(event) {
        var coords = point_it(event, this);
        tile = getTile(coords);
        if (tile.hasPhoto == true) {
            $j ("#active-tile").css("left", tile.left);
            $j ("#active-tile").css("top", tile.top);
            $j ("#active-tile").show();
        }
        else {
            inputDelayer();
            $j ("#active-tile").hide();
        }
    });
}

var inputDelayer = delayTimer(350);
function activeTileListener() {
    $j ('#active-tile').bind("mouseenter", function(event) {
        $j ('#mosiac-interact').unbind;
        inputDelayer(function() {
            var result = CatChowPink.Web.WebUtility.GetPhotoDetails(tile.photoPosition);
            var photoId = result.value.PhotoId;
            getPhotoSnippet(photoId);
            $j ("#tooltip").ajaxComplete(function(e) {
                $j (".large-thumb").bind("load", function(e) {
                    $j ("#tooltip").css("top", (tile.top - 170));
                    $j ("#tooltip-pointer").css("top", (tile.top - 50));
                    if (tile.left <= 550) {
                        $j ("#tooltip-pointer").css("left", (tile.left + 13));
                        $j ("#tooltip-pointer").removeClass();
                        $j ("#tooltip-pointer").addClass("pointer-right");
                        $j ("#tooltip").css("left", (tile.left + 61));
                    }
                    else if (tile.left >= 551) {
                        $j ("#tooltip-pointer").css("left", (tile.left - 53));
                        $j ("#tooltip-pointer").removeClass();
                        $j ("#tooltip-pointer").addClass("pointer-left");
                        $j ("#tooltip").css("left", (tile.left - 62) - $j ("#tooltip").width());
                    }
                    $j ("#tooltip").show();
                    $j ("#tooltip-pointer").show();
                });
            });
        });
    }).bind("mouseleave", function(event) {
        $j ("#tooltip").hide();
        $j ("#tooltip-pointer").hide();
        mosaicSubListener();
    });
}

function getPhotoSnippet(photoId) {
    $j .ajax({
		type: "GET",
		cache: true,
		url: "PhotoThumbnail.aspx",
		data: { id: photoId },
		success: function(data, textStatus) {
		    $j ("#tooltip").html(data);
		},
		error: function() {
			//console.warn("Error!");
		},
		dataType: "html"
	});
}

function getTile(coords) {
    var x = parseInt(coords.x / 10);
    var y = parseInt(coords.y / 10);
    if (mosaicState[y] == undefined) {
        return mosaicState[114][1];
    }
    return mosaicState[y][x];
}

function toolTipListener()
{
    $j ('.spawn-tool-tip').mouseover(function(e)
    {
        $j ('.tool-tip').toggle();
    });

    $j ('.spawn-tool-tip').mouseout(function(e)
    {
        $j ('.tool-tip').toggle();
    });
}

function getMosaicGrid() {
    if ($j ("#mosiac-interact").length == 0) return false;
    var gridObjects = CatChowPink.Web.WebUtility.GetMosaicGrid();
    var tiles = gridObjects.value;
    var tileLength = tiles.length;
    var position = 0;
    
    mosaicState = new Array(115);
    for (var y = 0; y < 115; y ++) {
        mosaicState[y] = new Array(87);
        for (var x = 0; x < 87; x++) {
            mosaicState[y][x] = {};
            if (tiles[position] != 0) {
                mosaicState[y][x].hasPhoto = true;
            } else {
                mosaicState[y][x].hasPhoto = false;
            }
            mosaicState[y][x].left = x * 10;
            mosaicState[y][x].top = y * 10;
            mosaicState[y][x].photoPosition = tiles[position];
            position = position + 1;
        }
    }
    mosaicListener();
}

function point_it(event, el) {
    var offset = $j (el).offset();
    pos_x = event.offsetX ? (event.offsetX) : event.pageX - offset.left;
    pos_y = event.offsetY ? (event.offsetY) : event.pageY - offset.top;
    var coords = {};
    coords.x = pos_x;
    coords.y = pos_y;
    return coords;
}

function storyFieldListener() {
    if ($j ("textarea.story-textfield").length == 0) return false;
    $j ("textarea.story-textfield").keyup(function(event) {
        textFieldLengthTracker(this, 1500, $j ('#story-textfield-count'));
    });
}

function textFieldLengthTracker(textField, max, charcountId) {
    if ($j (textField).val().length <= max) {
        charcountId.html(max - $j (textField).val().length);
    }
    else if ($j (textField).val().length >= max) {
        $j (textField).val($j (textField).val().substring(0, max));
    }
}

//Quiz Related below USES PROTOTYPE LIBRARY

//This is run as the user clicks radio buttons on the quiz.
function checkAnswer(itemClicked) {
    var answerGroup = itemClicked.parentNode.parentNode;
    var correctClicked = $(itemClicked).hasClassName('a');
    var allAnswers = $(answerGroup).select('li.quizSelection');
    var correctTextArea = $(answerGroup).select('li.quizResponse');
    var wrongTextArea = $(answerGroup).select('li.quizResponseWrong');
    for (i = 0; i < allAnswers.length; i++) {
        allAnswers[i].select('span.correctionIcon')[0].hide();
        allAnswers[i].select('span.correctionIcon')[0].removeClassName('correctionIconCorrect');
    }
    if (correctClicked) {
        itemClicked.previous('span').show();
        itemClicked.previous('span').addClassName('correctionIconCorrect');
        correctTextArea[0].show();
        wrongTextArea[0].hide();
    }
    else {
        itemClicked.previous('span').show();
        correctTextArea[0].hide();
        wrongTextArea[0].show();
    }
    allAnswersCorrect();
}

//Checks to see if the user has answered all 5 questions correctly and then shows or hides captcha and submit button accordingly.
function allAnswersCorrect() {
    var numOfCorrectAnswers = $$('.correctionIconCorrect');
    if (numOfCorrectAnswers.length >= 5) {
        $$('.quizNotComplete').each(function(notComplete) {
            notComplete.hide();
        });
        $$('.quizComplete').each(function(complete) {
            complete.show();
        });
    }
    else {
        $$('.quizNotComplete').each(function(notComplete) {
            notComplete.show();
        });
        $$('.quizComplete').each(function(complete) {
            complete.hide();
        });
    }
}

//Checks to see if the user is on the facts page but has made a mistake with the captcha or dirty word filter then sets all questions to correct.
function makeAllCorrect() {
    if ($('quizContainer')) {
        if ($$('.alert').length > 0) {
            $$('.a').each(function(itemToClick) {
                checkAnswer(itemToClick);
                itemToClick.checked = true;
            });
        }
    }
}

function checkCatValue()
{
    if ($('quizContainer')) {
        $$('table.radio-buttons tr td input').each(function(e) {
            if (e.checked == true) {
                if (e.value == "Yes") {
                    $$('.have-cats').each(function(e) {
                        e.show();
                    });
                }
                else {
                    $$('.have-cats').each(function(e) {
                        e.hide();
                    });
                }
            }
        });
    }
}

function setDonationCookie() {
    if ($$('.thankYouPage').length != 0) {
        var donateCookie = getCookie('CCPinkDonate');
        if (donateCookie != null || donateCookie != 'Yes') {
            setCookie('CCPinkDonate', 'Yes', 90, '/', '', '');
        }
    }
}

function alreadyDonatedRedirect() {
    var donateCookie = getCookie('CCPinkDonate');
    if (donateCookie == 'Yes') {
        if ($$('.finalThankYouPage').length <= 0 && $$('.certificate').length <= 0) {
            window.location = "Thanks.aspx"
        }
    }
}

if (document.getElementById('quizContainer'))
{
    document.observe('dom:loaded', function() {
        
        //alreadyDonatedRedirect();
        //setDonationCookie();
        makeAllCorrect();
        checkCatValue();
    });
}
