﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
var flashTitleIsReady = false;
var currentRoomTitle = '';
var jsReady = false;
var sysOp = '';
var currentPop = '';
var contactPage = false;
var popupOpen = false;

function CreateTitle()
{
//    $('#roomTitleReplace').flash(
//    {
//        id: 'flashRoomTitle',
//        name: 'flashRoomTitle',
//        src: '/swf/SEGOE_UI.swf?t=' + (new Date).valueOf() + ';',
//        width: 650,
//        height: 60,
//        bgcolor: '#FFFFFF',
//        wmode: 'transparent',
//        allowscriptaccess: 'always',
//        flashvars: { roomTitle: '', col: '0x000000' }
//    }, { update: false });

    var vars = {
        roomTitle: '',
        col: ''
    };
    var params = {
        wmode: 'transparent',
        bgcolor: '#FFFFFF',
        allowscriptaccess: 'always'
    };
    var attributes = {
        id: 'flashRoomTitle',
        name: 'flashRoomTitle'
    };
    var src = '/swf/SEGOE_UI.swf?t=' + (new Date).valueOf();

    swfobject.embedSWF(src, 'roomTitleReplace', '650', '60', '9.0.0', false, vars, params, attributes);
}

function CreateShowcase()
{
//    $('#showcaseReplace').flash(
//    {
//        id: 'flashShowcase',
//        name: 'flashShowcase',
//        src: '/swf/GotRadioHomePage.swf?t=' + (new Date).valueOf() + ';',
//        width: 935,
//        height: 395,
//        bgcolor: '#000000',
//        wmode: 'opaque',
//        allowscriptaccess: 'always'
    //    }, { expressInstall: true });

    var vars = false;
    var params = {
        wmode: 'opaque',
        bgcolor: '#000000',
        allowscriptaccess: 'always'
    };
    var attributes = {
        id: 'flashShowcase',
        name: 'flashShowcase'
    };
    var src = '/swf/GotRadioHomePage.swf?t=' + (new Date).valueOf();

    swfobject.embedSWF(src, 'showcaseReplace', '935', '395', '9.0.0', '/swf/expressInstall.swf', vars, params, attributes);
}

function init() {
    sysOp = $.browser.browser() + ' - ' + $.browser.OS();
    jsReady = true;

    CreateTitle();
    CreateShowcase();
    //swfobject.embedSWF(swfUrl, id, width, height, version, expressInstallSwfurl, flashvars, params, attributes, callbackFn);
    

//    




    //    $('#roomTitleReplace').flash({
    //        'id': 'flashRoomTitle',
    //        'src': '../../swf/SEGOE_UI.swf?t=' + (new Date).valueOf(),
    //        'width': '650',
    //        'height': '60',
    //        'allowfullscreen': 'true',
    //        'bgcolor': '#FFFFFF',
    //        'wmode': 'transparent',
    //        'allowscriptaccess': 'always',
    //        'flashvars': { 'roomTitle': '', 'col': '0x000000' }
    //    });

    //    $('#showcaseReplace').flash({
    //        'id': 'flashShowcase',
    //        'src': '../../swf/GotRadioHomePage.swf?t=' + (new Date).valueOf(),
    //        'width': '935',
    //        'height': '395',
    //        'allowfullscreen': 'true',
    //        'bgcolor': '#000000',
    //        'wmode': 'transparent',
    //        'allowscriptaccess': 'always'
    //    });

    $('#playerPullout').click(OpenPlayer);

    $('#alertMessageWrapper img').click(CloseMessage);

    $('#formFeedback').submit(function() {
        //alert('is valid?');
        var isValid = $("#formFeedback").validationEngine({ returnIsValid: true, scroll: false })
        if (isValid) {
            $('#feedbackContainer .formLoading').show();
            $('#feedbackContainer .btnSubmit').attr('disabled', 'disabled');
            var datamap = $('#formFeedback').serialize();
            $.post('/Contact.mvc/Feedback', datamap, function(data) {
                CloseFeedback();
                OpenMessage('Your feedback has been received, thank you for your input');
            }, 'json');
        }
        return false;
    });

    $('#formContestEntry').submit(function() {
        var isValid = $("#formContestEntry").validationEngine({ returnIsValid: true, scroll: false })
        if (isValid) {
            $('#ContestEntryContainer .formLoading').show();
            $('#ContestEntryContainer .btnSubmit').attr('disabled', 'disabled');
            var datamap = $('#formContestEntry').serialize();
            $.post('/Contact.mvc/ContestEntry', datamap, function(data) {
                CloseContestForm();
                OpenMessage('Your contest entry has been received, we will email you the results of the contest once it has concluded');
            }, 'json');
        }
        return false;
    });


    $('#formContactProgrammer').submit(function() {
        var isValid = $("#formContactProgrammer").validationEngine({ returnIsValid: true, scroll: false })
        if (isValid) {
            $('#ContactProgrammerContainer .formLoading').show();
            $('#ContactProgrammerContainer .btnSubmit').attr('disabled', 'disabled');
            var datamap = $('#formContactProgrammer').serialize();
            $.post('/Contact.mvc/ContactProgrammer', datamap, function(data) {
                CloseContactProgrammer();
                OpenMessage('Your message has been sent, our programmers should respond soon.');
            }, 'json');
        }
        return false;
    });


    if (contactPage) {

        $('#newContactFormParent').replaceWith($('#GeneralContactContainer'));
        $('#GeneralContactContainer').css("position", "relative");
        $('#GeneralContactContainer .btnClose').hide();
        $('#GeneralContactContainer').show();
    }
    $('#formGeneralContact').submit(function() {
        var isValid = $("#formGeneralContact").validationEngine({ returnIsValid: true, scroll: false })
        if (isValid) {
            $('#GeneralContactContainer .formLoading').show();
            $('#GeneralContactContainer .btnSubmit').attr('disabled', 'disabled');
            var datamap = $('#formGeneralContact').serialize();
            $.post('/Contact.mvc/GeneralForm', datamap, function(data) {
                CloseGeneralContact();
                OpenMessage('Your message has been sent, we will respond within 2 business days.');
            }, 'json');
        }
        return false;
    });

    $('#backgroundPopup').click(function() {
        ClosePopup();
    });

    $('#linkTopSongs').click(function() {
        OpenTopSongs();
        return false;
    });

    $('#contact').click(function() {
        OpenGeneralContact();
        return false;
    });

    var volume = $.cookies.get('playerVolume');
    WritePlayer(false, 0, volume);

    GetTwitterStatus();
    RefreshBanners();
    setInterval(RefreshBanners, 90000);

}


function GetTwitterStatus() {
    var tu = 'gotradio'; // set user name
    var tFormat = 'json'; // set format, you really don't have an option on this one
    var tUrl = 'http://api.twitter.com/1/statuses/user_timeline/' + tu + '.' + tFormat + '?callback=?'; // make the url
    $.getJSON(tUrl, function(tweet) { // get the tweets
        $("#twitterContent").html(tweet[0].text); // get the first tweet in the response and place it inside the div
    });
}



function showcaseIsReady() {
    return jsReady;
}

function titleIsReady() {
    flashTitleIsReady = true;

    if (jsReady)
        UpdateRoomTitle();

    return jsReady;
}

function UpdateRoomTitle() {
    var title = currentRoomTitle.trim();
    $('#flashRoomTitle').externalInterface({ method: 'changeRoomTitle',
        args: '' + currentRoomTitle + ''
    });
    $('.flashRoomTitle').externalInterface({ method: 'changeRoomTitle',
        args: '' + currentRoomTitle + ''
    });
    /* ,
    success: function(data) { alert('success: ' + currentRoomTitle + ' was sent'); },
    error: function(error) { alert('there was an error: ' + error); }*/
}




var topSongsLoaded = false;
function OpenTopSongs() {
    currentPop = '#TopSongsContainer';
    centerPopup(currentPop);
    loadPopup(currentPop);

    if (!topSongsLoaded) {
        $('#TopSongsContainer .formLoading').show();
        $('#topSongsList').html('');

        var loc = '/MusicRoom.mvc/Stations';
        var stationHtml = '';
        $.getJSON(loc, function(json) {
            $('#TopSongsContainer .formLoading').fadeOut('normal', function() {
                $.each(json, function(i, station) {
                    $('#topSongsList').append('<div class="topSongStationName">' + station.name + '</div><div class="topSong"><strong>' + station.topSongArtist + '</strong> - ' + station.topSongName + ' <a href="http://www.amazon.com/exec/obidos/external-search?tag=gotradiocom-20&index=digital-music&field-keywords=' + station.topSongArtist + ' - ' + station.topSongName + '" target="_blank" class="download"></a> <a href="#" onclick="PlayNow(' + station.topSongID + ', ' + station.id + '); return false;" class="playNow"></a></div>');
                });
                centerPopup(currentPop);
                topSongsLoaded = true;
            });
        });
    }

}
function CloseTopSongs() {
    disablePopup('#TopSongsContainer');
}


function ClosePopup() {
    if (currentPop != '')
        disablePopup(currentPop);
}

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}

function SetActiveRoom(selectedID) {
    var newName = '';
    var map = $('#roomMenu li');
    $.each(map, function(key, value) {
        $(value).removeClass('active');
        var currentID = GetRoomID($(value).attr('id'));
        if (currentID == selectedID) {
            $(value).addClass('active');
            newName = $(value).children('span').text();
            $(value).children('ul').slideDown('fast');
        } else {
            $(value).children('ul').slideUp('fast');
        }
    });



    SetStationName(newName);

    LoadStations(selectedID);
}
function GetRoomID(name) {
    return name.replace('roomLink', '');
}

function SetStationName(name) {
    currentRoomTitle = name;
    UpdateRoomTitle();
    //alert(name);
    //$('#roomTitle').html('');

}

function LoadStations(roomID) {
    var loc = '/MusicRoom.mvc/details/' + roomID;

    /***
    process
    1) fade out channel content
    2) once fade is done, make JSON call
    3) change content to show loader
    4) fade in loader
    5) once JSON is loaded, fade out loader
    6) change content to the new stations
    7) fade IN stations
    */
    //
    $('#stationList').fadeOut('normal', function() {
        $('#stationList').html('<div class="loading"><img src="../../img/loading3.gif" width="32" height="32" alt="" align="middle" /> &nbsp; &nbsp; Loading Station Info...</div>');
        $('#stationList').fadeIn('normal', function() {
            $.getJSON(loc, function(json) {
                $('#stationList').fadeOut('normal', function() {
                    $('#stationList').html('');
                    $.each(json.MusicRoom_Stations, function(i, musicRoomStation) {
                        CreateStation(musicRoomStation.MusicStation);
                    });
                    $('#stationList').fadeIn('normal', function() { });
                    LoadDescriptionToolTips();
                    LoadHistoryHandles();
                });
            });
        });
    });

}

function LoadHistoryHandles() {

    $('.stationHistory-closed').click(function() {
        var stationID = $(this).attr('data-stationID');
        var content = $(this).parent().children('.stationHistoryContent');
        var loaded = (content.html() != '');

        if ($(this).hasClass('stationHistory-closed')) {

            $(this).removeClass('stationHistory-closed');
            $(this).addClass('stationHistory-open');

            if (!loaded) {
                content.html('<div class="loading"><img src="../../img/loading3.gif" width="32" height="32" alt="" align="middle" /> &nbsp; Loading History...</div>');
                $.post('/MusicRoom.mvc/GetHistory/' + stationID, { recordCount: '10' }, function(data) {
                    //create rows
                    content.html('');
                    $.each(data, function(i, history) {
                        if (i > 0)
                            content.append('<div class="currentSong"><a href="http://www.amazon.com/exec/obidos/external-search?tag=gotradiocom-20&index=digital-music&field-keywords=' + history.artist + ' - ' + history.title + '" target="_blank" class="download"><div class="tooltip">Download this song<b class="border-notch"></b><b class="notch"></b></div></a> <a href="#" onclick="PlayNow(' + history.songID + ', ' + history.stationID + '); return false;" class="playNow"><div class="tooltip">Start stream with this song<b class="border-notch"></b><b class="notch"></b></div></a><span title="' + history.artist + ' - ' + history.title + '"><strong>' + history.artist + '</strong> - ' + history.title + '</span></div>');
                        // <div class="historyCurrentSong"><strong>' + history.artist + '</strong> - ' + history.title + ' <a href="http://www.amazon.com/exec/obidos/external-search?tag=gotradiocom-20&index=digital-music&field-keywords=' + history.artist + ' - ' + history.title + '" target="_blank" class="download">download</a> <a href="#" onclick="PlayNow(' + history.songID + ', ' + history.stationID + '); return false;" class="playNow">play now</a></div><br class="clearfloat" />');
                    });
                    LoadDescriptionToolTips();

                }, 'json');
            }

        } else {
            $(this).removeClass('stationHistory-open');
            $(this).addClass('stationHistory-closed');
        }
        content.toggle();

    }
	);
}

function LoadDescriptionToolTips() {

    $('.stationDescription span').hover(function() {
        $(this).parent().children('.tooltip').fadeIn('fast'); //.show()
    },
        function(evt) {
            $(this).parent().children('.tooltip').fadeOut('fast'); //.hide();
        });

    $('.playNow').hover(function() {
        $(this).children('.tooltip').fadeIn(100);
    },
        function(evt) {
            $(this).children('.tooltip').fadeOut(100);
        });

    $('.download').hover(function() {
        $(this).children('.tooltip').fadeIn(200);
    },
    function(evt) {
        $(this).children('.tooltip').fadeOut(200);
    });
    //    $('.stationDescription span').tooltip({
    //        //tip: '#demotip',  no tip specified assumes next tip
    //        effect: 'slide',
    //        slideOffset: 10,
    //        slideInSpeed: 100,
    //        slideOutSpeed: 100
    //    });//'#demotip');

    //var map = $('.stationDescription span');

    //$('.stationDescription span')
    //$('.stationDescription span').tooltip({ effect: 'slide'}); 


    //    $.each(map, function(key, value) {
    //        var description = $(value).children('span').text();

    //        // If counter reaches maximum, reset

    //            $('.stationDescription span').tooltip({
    //                tip: $(this).parent().children('.callout'), //'#demotip',  //no tip specified assumes next tip
    //                effect: 'slide',
    //                slideOffset: 10,
    //                slideInSpeed: 100,
    //                slideOutSpeed: 100
    //            });//'#demotip');


    //$(value).simpletip({ fixed: true, position: '' + dir + '', content: description });
    //});
}

function CreateStation(station, roomID) {
    var html = '';
    html += '<div class="station"><a name="' + station.name + '" />';
    html += '   <div class="stationImg">';
    html += '       <a class="imgBackground" href="#" onclick="PlayStation(' + station.id + ');return false;"><img src="/img/g_album.png" width="100" height="100" /></a>';
    html += '       <a class="imgCover" href="#" onclick="PlayStation(' + station.id + ');return false;"><img src="' + station.img + '" width="100" height="100" /></a>';
    //html += '       <div class="imgCover" style="background-image: url(' + station.img + ');"></div>';
    html += '   </div>';
    html += '   <div class="stationInfo">';
    html += '       <div class="currentListeners">Current Listeners: <strong>' + Math.round(station.currentListenerCount*2.13) + '</strong>'
    html += '           <a href="#" onclick="OpenContactProgrammer(' + station.id + ', \'' + station.name.replace("'", "\\'") + '\', ' + station.programmerID + ', \'' + station.programmerName + '\'); return false;"  class="contactProgrammer">Programmed by ' + station.programmerName + '</a></div>';
    html += '       <a href="#" onclick="PlayStation(' + station.id + ');return false;" class="stationName">' + station.name + '</a>';
    html += '       <div class="stationDescription"><span>Station Description</span><div class="tooltip">' + station.description + '<b class="border-notch"></b><b class="notch"></b></div></div>';
    html += '       <div class="topSong"><a href="http://www.amazon.com/exec/obidos/external-search?tag=gotradiocom-20&index=digital-music&field-keywords=' + station.topSongArtist + ' - ' + station.topSongName + '" target="_blank" class="download"><div class="tooltip">Download this song<b class="border-notch"></b><b class="notch"></b></div></a> <a href="#" onclick="PlayNow(' + station.topSongID + ', ' + station.id + '); return false;" class="playNow"><div class="tooltip">Start stream with this song<b class="border-notch"></b><b class="notch"></b></div></a><span title="' + station.topSongArtist + ' - ' + station.topSongName + '"><strong>' + station.topSongArtist + '</strong> - ' + station.topSongName + '</span></div>';
    html += '       <div class="currentSong">';
    html += '           <a href="http://www.amazon.com/exec/obidos/external-search?tag=gotradiocom-20&index=digital-music&field-keywords=' + station.currentSongArtist + ' - ' + station.currentSongName + '" target="_blank" class="download"><div class="tooltip">Download this song<b class="border-notch"></b><b class="notch"></b></div></a><span title="' + station.currentSongArtist + ' - ' + station.currentSongName + '"><i>Now Playing:</i> <strong>' + station.currentSongArtist + '</strong> - ' + station.currentSongName + '</span>';
    html += '       </div>';
    html += '   </div>';
    html += '   <div class="stationHistory-closed" data-stationID="' + station.id + '">View Playlist History</div><div class="stationHistoryContent"></div>';
    html += '</div>';

    $('#stationList').append(html);
}


function SetHomeRoom() {
    var newOptions = {
        //domain: '*.gotradio.com',
        expiresAt: new Date(2020, 1, 1)
    };
    var roomID = GetSelectedRoomID()
    $.cookies.set('homeRoom', roomID, newOptions);

    OpenMessage('Your home room has been saved');
}

function OpenMessage(message, time) {
    if (time != null || time == undefined)
        time = 5000;
    $('#alertMessage').text(message);
    $('#interactionMessage').show('fast', function() {
        window.setTimeout(CloseMessage, time);
    });
}
function CloseMessage() {
    $('#interactionMessage').hide('fast');
    $('#alertMessage').text('');
}

function ReadHomeRoom(listName) {
    var value = $.cookies.get('homeRoom');

    if (value == null)
        value = ReturnFirstRoomID();

    return value;
}

function ReturnFirstRoomID() {
    var list = $('#roomMenu li');
    var roomname = null;
    var id = null;

    $.each(list, function(key, value) {
        roomname = $(value).attr('id');
        id = GetRoomID(roomname);
        return false;
    });

    return id;
}

function GetSelectedRoomID() {
    var list = $('#roomMenu li');
    var id = null;

    $.each(list, function(key, value) {
        if ($(value).hasClass('active')) {
            id = $(value).attr('id');
            return false;
        }
    });

    return GetRoomID(id);
}



function centerPopup(formName) {
    //request data for centering  
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $(formName).height();
    var popupWidth = $(formName).width();
    //centering
    $(formName).css({
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });

}

//disabling popup with jQuery magic!
function disablePopup(formName) {
    //disables popup only if it is enabled
    if (popupOpen) {
        $("#backgroundPopup").fadeOut("fast");

        $(formName + ' .formLoading').hide();
        $(formName + ' .btnSubmit').removeAttr("disabled");
        $(formName + ' .formInput').val('');
        $(formName).fadeOut("fast");
        popupOpen = false;
        currentPop = '';
        $('.formError').remove();
    }
}

//loading popup with jQuery magic!
function loadPopup(formName) {
    //loads popup only if it is disabled
    if (!popupOpen) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("fast");
        $(formName).fadeIn("fast");
        popupOpen = true;
    }

    //only need force for IE6
    $("#backgroundPopup").css({
        "height": document.documentElement.clientHeight
    });
}


function setConfirmUnload(on) {

    window.onbeforeunload = (on) ? unloadMessage : null;

}

function unloadMessage() {

    return 'You are currently trying to leave this page.  If you navigate away, your music streaming will stop.';

    //$(':input', document.myForm).bind("change", function() { setConfirmUnload(true); }); // Prevent accidental navigation away
}
