var SLIDER_POS_COOKIE = "_slider";

jQuery.extend({
    config: {
        sliderleftmargin: 0,
        frontstage: {
            divID: 'stage'
        },
        BodyEventHandlerToCancelToolTip: ['onclick', 'onmousedown'],
        ToolTipWrapperID: 'ChVToolTip',
        ToolTipWrapperNode: '',
        weekdays: new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"),
        currentlbl: '',
        oldlbl: null,
        footer: null
    },
    source: {
        JSON: null,
        SubNavJson: null,
        GetModuleFromModuleLookUp: function(_id, _src) {
            //return a module object in the passed JSON Array
            for (var i = 0; i < _src.ModuleLookup.length; i++) {
                if (_src.ModuleLookup[i].Key == _id) {
                    return _src.ModuleLookup[i];
                    break;
                }
            }
            return false;
        }
    },
    
    page: {
        IsUserAuthenticated: false,
        assets: {
            backstage: null,
            segmentManger: null,
            frontstage: null,
            subnavigations: null,
            pageModuleContents: null,
            pageSubNavModuleContents: null,
            HiddenModuleCollectionsBySubNav: null,
            TopMainNav: null,
            NavTools: null,
            VideoPlayListController: null,
            VideoPlayListControllerObject: null,
            ReserveddoSubNavigationCallbackFunc: null
        },
        ui: {
            templates: {
                ModuleSkelton: {
                    create: function(_class, _id) {
                        return $('<div class="' + _class + '" id="' + _id + '"><div class="m_header"><div class="topNav"><span class="m_contentType"></span><span class="m_plusSignTrigger"></span></div><div class="m_title"></div></div><div class="m_body"></div><div class="m_subMenu"></div></div>');
                    }
                },
                QueryStrings: {
                    create: function(_obj) {
                        return "?category=" + _obj.category + "&sliderposition=" + _obj.parameters[0] + "&subNavigationOpened=0";
                    }
                },
                throbber: function() {
                    //check
                    return $('<div class="throbber"><img src="images/testdata/ajax-loader.gif" alt="" width="28px" height="28px"/></div>');
                }
            },
            url: {
                hash: function() {
                    return (!window.location.hash == '');
                },
                getKeyValue: function(_key, _src) {
                    var queryPairs;
                    if (_src == undefined) {
                        queryPairs = (window.location.hash.split('?'));
                    } else 
                        queryPairs = _src;
                    
                    for (var i = 0; i < queryPairs.length; i++) {
                        var pair = queryPairs[i].split('=');
                        
                        if (pair[0].toUpperCase() == _key.toUpperCase()) {
                            return pair[1];
                            break;
                        }
                    }
                },
                getPathName: function() {
                    var urlContentPathString = window.location.pathname;
                    urlContentPathString = urlContentPathString.substring(1, urlContentPathString.length);
                    
                    return urlContentPathString;
                },
                getHashName: function() {
                    var urlContentPathString = window.location.hash;
                    urlContentPathString = urlContentPathString.substring(1, urlContentPathString.length);
                    return urlContentPathString;
                },
                
                
                ajaxPointerString: "xml/ModulesTestData.xml",
                ajaxPointerStringStatic: 'xml/',
                ajaxPointer: "handlers/getmodules.ashx",
                ajaxEndPointInitialRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/GetBackstage",
                ajaxEndPointSliderRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/GetSliderUpdate",
                ajaxEndPointSubNavRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/GetBackstage",
                ajaxEndPointInitialRequestNoPosition: "http://" + window.location.hostname + "/ContentModuleService.svc/GetBackstage",
                ajaxPollSubmissionRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/SubmitPollResponse",
                ajaxPollResultRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/GetPollResultsHtml?pollId=",
                ajaxRequestToolTipContent: "http://" + window.location.hostname + "/ContentModuleService.svc/GetTooltip?tooltipName=",
                ajaxGetTrackInfoHtml: "http://" + window.location.hostname + "/MediaPlayerService.svc/GetTrackInfoHtml?",
                ajaxGetNextPollHtml: "http://" + window.location.hostname + "/ContentModuleService.svc/GetNextPollHtml?pollId=",
                ajaxGetTrackInfoHtml: "http://" + window.location.hostname + "/MediaPlayerService.svc/GetTrackInfoHtml?",
                ajaxCompetitionSubmissionRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/SubmitCompetitionEntry",
                ajaxCompetitionConfirmingRequest: "http://" + window.location.hostname + "/ContentModuleService.svc/SubmitCompetitionEntry",
                ajaxUserprofileUpdate: "http://" + window.location.hostname + "/ContentModuleService.svc/DataEntryResult"
            
            }
        }
    
    },
    util: {
        Int: function(d_x, d_y) {
            return isNaN(d_y = parseInt(d_x)) ? 0 : d_y;
        },
        
        
        visibility: {
            hideById: function(_id) {
                $("#" + _id).css('visibility', 'hidden');
            },
            showById: function(_id) {
                $("#" + _id).css('visibility', 'visible');
            }
        },
        blockElementAttribute: {
            none: function(_id) {
                $("#" + _id).css('display', 'none');
            },
            block: function() {
                $("#" + _id).css('display', 'block');
            }
        },
        
        EventBubbleBlockerFactory: function(theNode) {
            var count = 0;
            var str = '';
            if (theNode.hasChildNodes()) {
            
                if (theNode.nodeType == 1) {
                    var AssignedFuncToNode;
                    try {
                        for (var i = 0; i < $.config.BodyEventHandlerToCancelToolTip.length; i++) {
                            AssignedFuncToNode = '';
                            AssignedFuncToNode = theNode[$.config.BodyEventHandlerToCancelToolTip[i]];
                            if (AssignedFuncToNode == undefined || typeof AssignedFuncToNode != 'function') {
                                theNode[$.config.BodyEventHandlerToCancelToolTip[i]] = $.util.CancelEventBubbles;
                            }
                        }
                    } catch (e) {
                        //alert (e);
                    }
                    count++;
                    for (var i = 0; i < theNode.childNodes.length; i++) {
                        count += $.util.EventBubbleBlockerFactory(theNode.childNodes[i]);
                    }
                }
            }
            return count;
        },
        CancelEventBubbles: function(e) {
            if (!e) {
                var e = window.event;
                e.cancelBubble = true;
            }
            if (e.stopPropagation) {
                e.stopPropagation();
                
            }
            
            
        },
        getAbsolutePageXYPosition: function(obj_node) {
            var myX, myY;
            myX = myY = 0; //helper variable
            while (obj_node) {
                myX += parseInt(obj_node.offsetLeft);
                myY += parseInt(obj_node.offsetTop);
                obj_node = obj_node.offsetParent || null;
            }
            
            return {
                x: myX,
                y: myY
            };
        },
        getRandomInt: function(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
        
    }


});


$(document).ready(function() {

    //Remove a dom containing static contents
    $('#StaticContentHolder').remove();
    
    //Instantiate Google tracker
    //pageTracker = _gat._getTracker("UA-6904600-1");
    //pageTracker._trackPageview();
    
    $("#Main").hide();
    
    
    ////////////////////////USER AUTHENTICATIONS ////////////////////////
    $.getJSON('http://' + window.location.hostname + '/UserAccountService.svc/CheckAuthentication', function(theAuthentication) {
    
        if (theAuthentication.d.IsAuthenticated) {
            $(this).UpdateLblForUserAuthentication({
                status: "Login",
                displayname: theAuthentication.d.UserName
            });
        }
    });
    
    
    ////// Search box initialization //////
    
    $('#fullTxtSearchTerm').keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            Amnesia.Search.doArtistSearchFromPageHeader();
            return false;
        } else {
            return true;
        }
    })
    
    
    delayedCalls();
    
});


function SubmitPoll(_pollId) {
    var pollNode = $('#pollList').eq(0);
    var pollBox = $('#pollsWrap').eq(0);
    
    $(pollNode).find('input').each(function() {
        if (this.type == 'radio' && this.name == _pollId) {
            if (this.checked) {
                var _postString = '{"PollAnswerId":"' + this.value + '","PollId":"' + this.name + '"}';
                
                $.ajax({
                    type: "POST",
                    url: $.page.ui.url.ajaxPollSubmissionRequest,
                    dataType: "Json",
                    contentType: "application/json",
                    data: _postString,
                    success: function(Htmldata) {
                        $.getJSON($.page.ui.url.ajaxPollResultRequest + _pollId, function(Htmldata) {
                            $(pollBox).html(Htmldata.Content);
                            
                            //draw bar chart
                            var _answerCounter = 0;
                            var _totalVotes = 0;
                            var _votesArray = [];
                            var _BarMaxLength = parseInt($(pollNode).find('.barWrap').css('width'));
                            
                            //find out the total number of votes
                            $(pollNode).find('.resultValue').each(function(i, val) {
                                _answerCounter = i;
                                _totalVotes += parseInt($(val).text());
                            });
                            
                            //arrange each entity by assigning index and amount of share in % of total
                            $(pollNode).find('.resultValue').each(function(i, val) {
                                _votesArray[_votesArray.length] = {
                                    tdindex: i,
                                    voteShare: Math.round(parseInt($(val).text()) / _totalVotes * 100)
                                }
                            });
                            
                            //Finally draw a chart
                            for (var d = 0; d < _votesArray.length; d++) {
                                $(pollNode).find('.bar').get(_votesArray[d].tdindex).style.width = Math.floor(_BarMaxLength * _votesArray[d].voteShare / 100) + 'px';
                            }
                        });
                    }
                });
                
            }
        };
            });
}


function GetPollResults(_pollId) {
    var pollNode = $('#pollList').eq(0);
    var pollBox = $('#pollsWrap').eq(0);
    $.ajax({
        type: "GET",
        url: $.page.ui.url.ajaxPollResultRequest + _pollId,
        dataType: "json",
        contentType: "application/json",
        success: function(data) {
            $(pollBox).html(data.Content);
            
            //draw bar chart
            var _answerCounter = 0;
            var _totalVotes = 0;
            var _votesArray = [];
            var _BarMaxLength = parseInt($(pollNode).find('.barWrap').css('width'));
            
            //find out the total number of votes
            $(pollNode).find('.resultValue').each(function(i, val) {
                _answerCounter = i;
                _totalVotes += parseInt($(val).text());
            });
            
            //arrange each entity by assigning index and amount of share in % of total
            $(pollNode).find('.resultValue').each(function(i, val) {
                _votesArray[_votesArray.length] = {
                    tdindex: i,
                    voteShare: Math.round(parseInt($(val).text()) / _totalVotes * 100)
                }
            });
            
            
            //Finally draw a chart
            for (var d = 0; d < _votesArray.length; d++) {
                $(pollNode).find('.bar').get(_votesArray[d].tdindex).style.width = Math.floor(_BarMaxLength * _votesArray[d].voteShare / 100) + 'px';
            }
        }
    });
    
}

function GetNextPollHtml(_pollId) {
    var pollBox = $('#pollsWrap').eq(0).parent().parent();
    $.getJSON($.page.ui.url.ajaxGetNextPollHtml + _pollId, function(data) {
        $(pollBox).html(data.Content);
    });
}


function FinaliseQuestionBundleIDIndexForm() {
    var _node = $('.competitionform[QuestionBundleIDs]').get(0);
    var IdArray = $(_node).attr('QuestionBundleIDs').split(',');
    _node.setAttribute('QuestionBundleIDs', IdArray);
    
}


function ConvenientDebugFunc() {
    //alert($.fn.piroBox = null);
    //alert($.fn.piroBox);
    //displaySource();
    //GenerateQuestionBundleIDIndex()

}

function GetGalleryByPageNumer(_node, _pageNum) {
    var theDirection;
    
    
    var _p = FindParent(_node);
    
    if (_p) {
    
        var galleryName = _node.getAttribute('data');
        
        $.getJSON('/ContentModuleService.svc/GetGalleryImagesHtml?galleryName=' + galleryName + "&pageNumber=" + _pageNum, function(data) {
        
            $(_p).empty();
            c = data.Content;
            
            _p.innerHTML = data.Content;
            $(_p).find('[jsClass]').each(function() {
                $.util.JSParser(this);
            });
        });
    }
    
}

function GetGallery(_node) {
    var _p = FindParent(_node);
    if (_p) {
        b = _p;
    };
    
    
    $.getJSON('/ContentModuleService.svc/GetGalleryImagesHtml?galleryName=' + _node.getAttribute('data'), function(data) {
        $(_p).empty();
        c = data.Content;
        _p.innerHTML = data.Content;
        
        $(_p).find('ul.quintCol').get(0).addresses = data.ImageUrls;
        $(_p).find('ul.quintCol').get(0).lbLabel = data.ImageLabels;
        $.scrollTo('#keyPhotoGalleries', 800);
        $(_p).find('[jsClass]').each(function() {
            $.getScript('js/' + $(this).attr('jsClass') + '.js');
        });
        
        
    });
}

function ViewAllGalleries(_node) {
    var _p = FindParent(_node);
    if (_p) {
    
        $.getJSON('/ContentModuleService.svc/GetAllGalleriesHtml?yearFilter=all&pageNumber=1', function(data) {
            $(_p).empty();
            c = data.Content;
            _p.innerHTML = data.Content;
            $.scrollTo('#keyPhotoGalleries', 800);
            window.location.hash = '/Social/Galleries';
            $('.galleryListUnit').parent().find('[jsClass]').each(function() {
                $.getScript('js/' + $(this).attr('jsClass') + '.js');
            });
        });
    }
}

function ViewAllGalleriesByYearPage(_node, _year, _page) {
    var _p = FindParent(_node);
    if (_p) {
    
        $.getJSON('/ContentModuleService.svc/GetAllGalleriesHtml?yearFilter=' + _year + '&pageNumber=' + _page, function(data) {
            $(_p).empty();
            c = data.Content;
            _p.innerHTML = data.Content;
            $.scrollTo('#keyPhotoGalleries', 800);
            $('.galleryListUnit').parent().find('[jsClass]').each(function() {
                $.getScript('js/' + $(this).attr('jsClass') + '.js');
            });
        });
    }
}


function FindParent(d_o) {
    var _pNode = 0;
    while (d_o) {
        d_o = d_o.offsetParent || null;
        if (d_o.className == 'module container') {
            _pNode = d_o;
            d_o = null;
        }
    }
    return _pNode;
}


function FindParentByTagNameAndClass(d_o, _param) {
    var _pNode = 0;
    
    //alert(d_o.tagName)
    while (d_o) {
        //alert(d_o.tagName)
        d_o = d_o.offsetParent || null;
        
        if (d_o != null) {
            if ((d_o.className == _param.className) && (d_o.tagName.toUpperCase() == _param.tag.toUpperCase())) {
                _pNode = d_o;
                d_o = null;
            }
        }
        
        
    }
    return _pNode;
}

var dbg = {
    _QuestionBundleObjects: '',
    _requestString: '',
    _nodes: '',
    _response: '',
    newLocation: null,
    historyObject: null,
    history: '',
    que: '',
    SegmentCollection: '',
    cursorPosition: '',
    modulePositions: '',
    string: ''

};

function getOnTimeOut(aVariable) {
    return function() { // no  params
        //alert(parseInt(aVariable.timeSignatureAtEntry) - parseInt(newTimeStamp));
        alert(aVariable + " is fired");
    }
}

function AlertMe(_node) {
    $($(_node).parent("div")).each(function() {
        $(this).data("selected", _node);
    })
}

function AlertMeOnCheckBox(_node) {
    if (_node.checked) {
        $($(_node).parent("div")).each(function() {
            this.dataContainer = addToList(this.dataContainer, {
                _key: _node.value,
                _value: true
            })
            alert(this.dataContainer.length);
            //$(this).data(_node.value, true);
        });
    } else {
        $($(_node).parent("div")).each(function() {
            this.dataContainer = addToList(this.dataContainer, {
                _key: _node.value,
                _value: false
            })
            alert(this.dataContainer.length);
        })
    }
}

function addToList(_nodeAttribute, _object) {
    try {
        var IsAlreadyListed = false;
        for (var i = 0; i < _nodeAttribute.length; i++) {
            if (_nodeAttribute[i].key == _object._key) {
                alert('in');
                _nodeAttribute[i].value = _value;
                IsAlreadyListed = true;
                break;
            }
        }
        if (!IsAlreadyListed) {
            _nodeAttribute[_nodeAttribute.length] = {
                key: _object._key,
                value: _object._value
            };
            alert('there');
        }
        return _nodeAttribute;
    } catch (e) {
        _nodeAttribute = [];
        _nodeAttribute[_nodeAttribute.length] = {
            key: _object._key,
            value: _object._value
        };
        return _nodeAttribute;
    }
    
}

function GetCompetitionResult() {
    $('.competitionform[QuestionBundleIDs] .compRadioType').each(function() {
        _QuestionBundleObjects[_QuestionBundleObjects.length] = {
            QuestionId: $(this).data("selected").name,
            AnswerText: "",
            AnswerId: $(this).data("selected").value
        }
    });
    
    $('.competitionform[QuestionBundleIDs] .compCheckBoxType').each(function() {
    
        // _QuestionBundleObjects[_QuestionBundleObjects.length] = {
        //     QuestionId: $(this).data("selected").name,
        //     AnswerText: "",
        //     AnswerId: $(this).data("selected").value
        // }
    });
    
}

var _QuestionBundleObjects = [];

// This is getting completely disorganised, IT REALLY NEEDS TO BE REFACTORED AT THE EARLIEST CHANCE
var Amnesia = {

    Search: {
        doArtistSearchFromPageHeader: function() {
            var _criteria = $('#fullTxtSearchTerm').val();
            _searchFilter = $('#searchFilter').val();
            if (_criteria != '' || _criteria !== "WHAT ARE YOU SEARCHING FOR?") {
                if (_searchFilter == "ARTIST") channelv.Page.navigationRequest("/Explore/ArtistSearch/" + _criteria);
                if (_searchFilter == "VIDEO") channelv.Page.navigationRequest("/Explore/VideoSearch/" + _criteria);
                if (_searchFilter == "SHOW") channelv.Page.navigationRequest("/Explore/ShowSearch/" + _criteria);
                if (_searchFilter == "COMPS") channelv.Page.navigationRequest("/Explore/CompetitionSearch/" + _criteria);
            }
        },
        doArtistSearchFromSearchResult: function(_node) {
            var _criteria = $(_node).parent('div.formSearchWrap').find('input.searchTerm').eq(0).val();
            _searchFilter = $('#searchFilterKey').val();
            if (_criteria != '' || _criteria !== "WHAT ARE YOU SEARCHING FOR?") {
                if (_searchFilter == "ARTIST") channelv.Page.navigationRequest("/Explore/ArtistSearch/" + _criteria);
                if (_searchFilter == "VIDEO") channelv.Page.navigationRequest("/Explore/VideoSearch/" + _criteria);
                if (_searchFilter == "SHOW") channelv.Page.navigationRequest("/Explore/ShowSearch/" + _criteria);
                if (_searchFilter == "COMPS") channelv.Page.navigationRequest("/Explore/CompetitionSearch/" + _criteria);
            }
        },
        cleartxtfield: function(_node) {
            $(_node).removeClass('emptyField');
        }
    },
    Request: {
        SelectedRequest: '',
        SelectedArtist: '',
        SelectedTrack: '',
        AuthenticationDispatcher: function(_AutomationId, _Artist, _Track) {
            Amnesia.Request.SelectedRequest = _AutomationId;
            Amnesia.Request.SelectedArtist = _Artist;
            Amnesia.Request.SelectedTrack = _Track;
            
            if ($.page.IsUserAuthenticated) {
                if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
                    Amnesia.Request.addRequest(_AutomationId);
                }
                if (amnesia.chv.Requests.vars.currentTab == 'CustomPls') {
                    amnesia.chv.Requests.addSongToLi(_AutomationId, _Artist, _Track);
                }
            } else {
                Amnesia.Request.getLoginForm();
            }
        },
        showTT: function(_node) {
            $(_node).ttshow('request');
        },
        hideTT: function(_node) {
            $(_node).tthide('request');
        },
        showImgGuidelineInTT: function(_node) {
            $(_node).ttshow('imgGuideLine');
        },
        hideImgGuidelineInTT: function(_node) {
            $(_node).tthide('imgGuideLine')
        },
        showPGShowInTT: function(_node) {
            $(_node).ttshow('pgGuideShow');
        },
        hidePGShowInTT: function(_node) {
            $(_node).tthide('pgGuideShow')
        },
        RequestToolTipTimeOutSetter: function(aVariable) {
            return function() { // no  params
                $(aVariable).addClass('showPop');
            }
        },
        getSearchPage: function(_node) {
            var theParent = $(_node).parents('div.m_body').eq(0);
            $.getJSON('/ContentModuleService.svc/GetRequestSearchPageHtml', function(data) {
                $(theParent).html(data.Content);
                //$.util.JSParser(data.Content);
                $('#requestsTab').addClass('set');
                $('#shoutoutsTab').removeClass('set');
            });
        },
        getShoutouts: function(_node) {
            $('#ReqSearch-Tab').css({
                'display': 'none'
            });
            if ($('.shoutComingSoon').length == 0) {
                $.get('/Templates/Request/shoutouts.htm', function(data) {
                
                    $('#Shoutouts-Tab').append(data);
                });
            } else {
                $('.shoutComingSoon').css({
                    'display': 'block'
                });
            }
            $('#Shoutouts-Tab').css({
                'display': 'block'
            });
            $('#CustomPls-Tab').css({
                'display': 'none'
            });
            $('#Requests-Tab').css({
                'display': 'none'
            });
            $('#requestsTab').removeClass('set');
            $('#shoutoutsTab').addClass('set');
            $('#customPlaylistTab').removeClass('set');
			if (amnesia.chv.Requests.vars.currentTab!='Shoutouts'){
				document.title = channelv.Page.currentTitle + ' - Shoutouts';
				channelv.Page.trackPage('/Shoutouts');
				channelv.Page.updateDblClickAd('/Shoutouts');
			}
            amnesia.chv.Requests.vars.currentTab = 'Shoutouts';
			
        },
        showRequests: function() {
            $('#Shoutouts-Tab').css({
                'display': 'none'
            });
            $('.shoutComingSoon').css({
                'display': 'none'
            });
            $('#ReqSearch-Tab').css({
                'display': 'block'
            });
            $('#CustomPls-Tab').css({
                'display': 'none'
            });
            $('#Requests-Tab').css({
                'display': 'block'
            });
			if (amnesia.chv.Requests.vars.currentTab!='Requests'){
				document.title = channelv.Page.currentTitle + ' - Make a Request';
				channelv.Page.trackPage('/Request');
				channelv.Page.updateDblClickAd('/Request');
			}
            amnesia.chv.Requests.vars.currentTab = 'Requests';
            $.getJSON('http://' + window.location.hostname + '/Services/RequestService.svc/GetTrackSearchHtml', function(data) {
                $('div#ReqSearch-Tab').empty();
                $('div#ReqSearch-Tab').html(data.Content);
                
                $('.top10AndLatest ul li').each(function(i) {
                    $(this).mouseover(function() {
                        Amnesia.Request.showTT(this);
                    });
                    $(this).mouseout(function(evt) {
                        Amnesia.Request.hideTT(this);
                    });
                    $(this).find('a').click(function() {
                        Amnesia.Request.AuthenticationDispatcher($(this).children('.automationId').text(), $(this).children('.artName').text(), $(this).children('.songTitle').text());
                        return false;
                    });
                });
            });
            $.getJSON('http://' + window.location.hostname + '/Services/RequestService.svc/GetRequestsHtml', function(data) {
                $('div#Requests-Tab').empty();
                $('div#Requests-Tab').html(data.Content);
            });
			
            $('#requestsTab').addClass('set');
            $('#shoutoutsTab').removeClass('set');
            $('#customPlaylistTab').removeClass('set');
        },
        getCustomPls: function() {
            $('#requestsTab').removeClass('set');
            $('#shoutoutsTab').removeClass('set');
            $('#customPlaylistTab').addClass('set');
            $('#Shoutouts-Tab').css({
                'display': 'none'
            });
            $('#ReqSearch-Tab').css({
                'display': 'block'
            });
            $('#CustomPls-Tab').css({
                'display': 'block'
            });
			if (amnesia.chv.Requests.vars.currentTab!='CustomPls'){
				document.title = channelv.Page.currentTitle + ' - Custom Playlist';
				channelv.Page.trackPage('/CustomPlaylist');
				channelv.Page.updateDblClickAd('/CustomPlaylist');
			}	
            amnesia.chv.Requests.vars.currentTab = 'CustomPls';
            $('.shoutComingSoon').css({
                'display': 'none'
            });
            $('#Requests-Tab').hide();
            $.getJSON('http://' + window.location.hostname + '/Services/RequestService.svc/GetTrackSearchHtml', function(data) {
                $('div#ReqSearch-Tab').empty();
                $('div#ReqSearch-Tab').html(data.Content);
                $('.top10AndLatest ul li').each(function(i) {
                    $(this).mouseover(function() {
                        Amnesia.Request.showTT(this);
                    });
                    $(this).mouseout(function(evt) {
                        Amnesia.Request.hideTT(this);
                    });
                    $(this).find('a').click(function() {
                        Amnesia.Request.AuthenticationDispatcher($(this).children('.automationId').text(), $(this).children('.artName').text(), $(this).children('.songTitle').text());
                        return false;
                    });
                });
            });
            $.getJSON('http://' + window.location.hostname + '/Services/RequestService.svc/GetCustomPlaylistHtml', function(data) {
                $('div#CustomPls-Tab').empty();
                $('div#CustomPls-Tab').html(data.Content);
                amnesia.chv.Requests.rebuildCollectedLi();
            });
            
            
        },
        getSearchResults: function() {
            var keywords = $('#requestSearch').get(0).value;
            
            $.getJSON('/Services/RequestService.svc/GetRequestSearchResultsHtml?keywords=' + keywords, function(data) {
            
                $('div.requestSearchResults').html(data.Content);
                $('div.requestSearchResults').find('li').each(function(i) {
                    $(this).mouseover(function() {
                        Amnesia.Request.showTT(this);
                    });
                    $(this).mouseout(function(evt) {
                        Amnesia.Request.hideTT(this);
                    });
                    
                    if (i % 2) {
                        $(this).addClass('even');
                    }
                });
            });
        },
        addRequest: function(trackId) {
            $('div#ReqSearch-Tab').css({
                'display': 'none'
            });
			document.title = channelv.Page.currentTitle + ' - Your request: ' + Amnesia.Request.SelectedArtist + ' - ' +Amnesia.Request.SelectedTrack;
			channelv.Page.trackPage('/Request/'+ Amnesia.Request.SelectedArtist.replace(" ", "+") + '/' +Amnesia.Request.SelectedTrack.replace(" ", "+"));
			channelv.Page.updateDblClickAd('/Request/'+ Amnesia.Request.SelectedArtist.replace(" ", "+") + '/' +Amnesia.Request.SelectedTrack.replace(" ", "+"));
            $.getJSON('/Services/RequestService.svc/GetRequestConfirmHtml?automationId=' + trackId, function(data) {
            
                $('div.reqStage').html(data.Content);
                
                Amnesia.ImgUploader();
                
                $('#requestDetails').validate({
                    submitHandler: Amnesia.Request.submitRequest,
                    onkeyup: false,
                    messages: {
                        profileImage: {
                            required: "You have to upload an image"
                        }
                    },
                    invalidHandler: function(form, validator) {
                        console.log('invalidHandler');
                        var parentLi;
                        
                        $('.errorField').each(function() {
                            $(this).removeClass('errorField')
                        });
                        $('.error').each(function() {
                            $(this).removeClass('error')
                        });
                        
                        var errorList = validator.errorList;
                        
                        if (errorList.length > 0) {
                            for (var i = 0; i < errorList.length; i++) {
                                parentLi = $(errorList[i].element).parent();
                                
                                if (errorList[i].message != "") {
                                    validator.showLabel(errorList[i].element, errorList[i].message);
                                }
                                $(parentLi).addClass('errorField');
                            }
                            
                            var errors = validator.numberOfInvalids();
                            var message = errors == 1 ? 'You missed 1 field. It has been highlighted below' : 'You missed ' + errors + ' fields.  They have been highlighted below';
                            $("#errorLabel .msg").html(message);
                            $('#errorLabel').show();
                        }
                    }
                });
            });
        },
        submitRequest: function() {
            // idArray is comma separated array of automationId's
            var displayName = $('#reqDisplayName').val();
            var state = $('#reqState :selected').val();
            var suburb = $('#reqSuburb').val();
            var comment = $('#reqComment').val();
            var imageUrl = $('#profileImage').val();
            var channel = $('#reqChannel :selected').val();
            //var show = $('#reqShows' + channel + ' :selected').val();
			var show = $('#reqShow').val();
            var sendEmail = $('#reqEmailMe').attr('checked');
            var update = false;
            var automationId = $('input[name=AutomationId]').val();
            
            var r = {};
            r.DisplayName = displayName;
            r.Suburb = suburb;
            r.State = state;
            r.ImageUrl = imageUrl;
            r.Notify = sendEmail;
            r.ShouldUpdateProfile = update;
            
            var trackRequests = [];
            
            if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
            	
				if (channel == 0 ) r.ChannelId = 1;
                else r.ChannelId = channel;
				// force show id for [v] or [v]hits
				if (channel==1 || channel == 0 ) show = 8;
				else show =   9;
				r.ShowId = show; 
				
				
               
                var q = {}
                q.AutomationId = automationId;
                q.Comment = comment;
                trackRequests[0] = q;
                svcStr = "/Services/RequestService.svc/SubmitRequest";
            } else {
                for (var i = 0; i < 5; i++) {
                    if (!isObjEmpty(amnesia.chv.Requests.vars.songsCollection[i])) {
                        var q = {}
                        q.AutomationId = amnesia.chv.Requests.vars.songsCollection[i].AutomationId;
                        q.Comment = amnesia.chv.Requests.vars.songsCollection[i].Comment;
                        trackRequests[i] = q;
                    }
                }
                svcStr = "/Services/RequestService.svc/SubmitCustomPlaylist";
            }

            r.TrackRequests = trackRequests;
			document.title = channelv.Page.currentTitle + ' - Request Submited';
			channelv.Page.trackPage('/RequestSubmited');
			channelv.Page.updateDblClickAd('/RequestSubmited');
			//duplicate ajax calls - one for each channel, or it goes ELSE if only one channel was selected
			if (channel == 0 ){
				r.ShowId = null;
				postStr = $.toJSON(r);
				$.ajax({
					type: "POST",
					data: postStr,
					url: "http://" + window.location.hostname + svcStr,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function(data) {
					
						if (data.IsValid) {
							postStr = "";
							
							r.ShowId = null;
							r.ChannelId = 2;
							postStr = $.toJSON(r);
							
							 $.ajax({
									type: "POST",
									data: postStr,
									url: "http://" + window.location.hostname + svcStr,
									contentType: "application/json; charset=utf-8",
									dataType: "json",
									success: function(data) {
									
										if (data.IsValid) {
											if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
												$('div.reqStage').html(data.HtmlToDisplay);
											} else {
												$('#custPlstWrap').html(data.HtmlToDisplay);
												amnesia.chv.Requests.vars.songsCollection = {};
												for (var i = 0; i < 5; i++) {
													amnesia.chv.Requests.vars.songsCollection[i] = {};
												};
												amnesia.chv.Requests.vars.currSlot = 0;
												
											}
										} else {
											$('label#requestSubmitError').empty().html(data.GeneralErrors).removeClass('hideDisplay');
											return false;
										}
										if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
											$('div.reqStage .step-RequestThanks .latestRequest ul li').each(function(i) {
												if (i % 2) {
													$(this).addClass('even');
												}
											});
											var _shiftCount = 2;
											var _shiftClass = 0;
											$('div.reqStage .step-RequestThanks .latestRequest ul li').each(function(i) {
											
												$(this).removeClass('even');
												if (_shiftClass == 0) $(this).addClass('even');
												if (_shiftCount == 2) {
													_shiftCount = 0;
													_shiftClass = (_shiftClass == 0) ? 1 : 0;
												}
												if (i % 2) {
													$(this).css('margin-right', '0px');
												}
												_shiftCount++;
											})
										}
										$.scrollTo('#requestsWrapper', 1000);
										
									}
								});
							return false;
							
						} else {
							$('label#requestSubmitError').empty().html(data.GeneralErrors).removeClass('hideDisplay');
							return false;
						}
						
						
						
					}
				});
				
			}
			else {  // just one channel selected
			
				postStr = $.toJSON(r);
				
				$.ajax({
					type: "POST",
					data: postStr,
					url: "http://" + window.location.hostname + svcStr,
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function(data) {
					
						if (data.IsValid) {
							if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
								$('div.reqStage').html(data.HtmlToDisplay);
							} else {
								$('#custPlstWrap').html(data.HtmlToDisplay);
								amnesia.chv.Requests.vars.songsCollection = {};
								for (var i = 0; i < 5; i++) {
									amnesia.chv.Requests.vars.songsCollection[i] = {};
								};
								amnesia.chv.Requests.vars.currSlot = 0;
								
							}
						} else {
							$('label#requestSubmitError').empty().html(data.GeneralErrors).removeClass('hideDisplay');
							return false;
						}
						if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
							$('div.reqStage .step-RequestThanks .latestRequest ul li').each(function(i) {
								if (i % 2) {
									$(this).addClass('even');
								}
							});
							var _shiftCount = 2;
							var _shiftClass = 0;
							$('div.reqStage .step-RequestThanks .latestRequest ul li').each(function(i) {
							
								$(this).removeClass('even');
								if (_shiftClass == 0) $(this).addClass('even');
								if (_shiftCount == 2) {
									_shiftCount = 0;
									_shiftClass = (_shiftClass == 0) ? 1 : 0;
								}
								if (i % 2) {
									$(this).css('margin-right', '0px');
								}
								_shiftCount++;
							})
						}
						$.scrollTo('#requestsWrapper', 1000);
						
					}
				});
            
			}
            
            return false;
        },
        submitRequestFastTrack: function(automationId) {
        	document.title = channelv.Page.currentTitle + ' - Request Submited';
			channelv.Page.trackPage('/RequestSubmited');
			channelv.Page.updateDblClickAd('/RequestSubmited');
            $.getJSON('http://' + window.location.hostname + '/Services/RequestService.svc/SubmitFastTrackRequest?automationId=' + automationId, function(data) {
            
                if (data.IsValid) {
                
                    $('div.reqStage').html(data.HtmlToDisplay);
                    
                    var _shiftCount = 2;
                    var _shiftClass = 0;
                    $('div.reqStage .step-RequestThanks .latestRequest ul li').each(function(i) {
                    
                        $(this).removeClass('even');
                        if (_shiftClass == 0) $(this).addClass('even');
                        if (_shiftCount == 2) {
                            _shiftCount = 0;
                            _shiftClass = (_shiftClass == 0) ? 1 : 0;
                        }
                        if (i % 2) {
                            $(this).css('margin-right', '0px');
                        }
                        _shiftCount++;
                    })
                    $.scrollTo('#requestsWrapper', 1000);
                } else {
                    $('label#requestSubmitError').empty().html(data.GeneralErrors).removeClass('hideDisplay');
                    return false;
                }
                
            });
        },
        getLoginForm: function() {
            $.getJSON('/ContentModuleService.svc/GetLoginFormHtml', function(data) {
                if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
                    $('div.reqStage').html(data.Content);
                    $.scrollTo('#Requests-Tab', 400);
                }
                if (amnesia.chv.Requests.vars.currentTab == 'CustomPls') {
                    $('div#custPlstLoginWrap').css({
                        "display": "block"
                    }).html(data.Content);
                    $('div#custPlstWrap').css({
                        "display": "none"
                    });
                    $.scrollTo('#CustomPls-Tab', 400);
                }
                
                $('.form_btn_Login').click(function() {
                    Amnesia.Login.doKeyStoneLogin(this, function() {
                        // Amnesia.Request.addRequest(Amnesia.Request.SelectedRequest);
                        if (amnesia.chv.Requests.vars.currentTab == 'Requests') {
                            Amnesia.Request.addRequest(Amnesia.Request.SelectedRequest);
                        }
                        if (amnesia.chv.Requests.vars.currentTab == 'CustomPls') {
                            $('div#custPlstWrap').css({
                                "display": "block"
                            });
                            $('div#custPlstLoginWrap').css({
                                "display": "none"
                            });
                            amnesia.chv.Requests.addSongToLi(Amnesia.Request.SelectedRequest, Amnesia.Request.SelectedArtist, Amnesia.Request.SelectedTrack);
                            
                        }
                    });
                    return false;
                });
            });
        },
        SwitchChannelShows: function(_node) {
            var selectedChannel = _node.options[_node.selectedIndex].value;
            
            $('select[name="show"]').css("display", "none");
            $('#reqShows' + selectedChannel).css("display", "block");
        },
        OnAireMsgValidation: function() {
            if ($('#reqComment').val().length <= 80) {
                $('#reqCommentLeft').html(80 - $('#reqComment').val().length);
            } else {
                alert('Please limit your message to 80 character length');
                $('#reqComment').val($('#reqComment').val().substring(0, 80));
            }
            
        }
    },
    ImgUploader: function() {
    
        var button = $('#button1');
        var interval;
        
        //if ($('#userProfileForm').length==0)$('.regImage').hide();
        new AjaxUpload(button, {
            action: '/Upload/FileHandler.ashx',
            name: 'myfile',
            onChange: function(file, ext) {
                if (ext && /^(jpg|bmp|jpeg|gif)$/.test(ext)) {
                    /* Setting data */
                    button.addClass('uploadingBtn');
                    this.disable();
                    
                } else {
                
                    // extension is not allowed
                    alert('Sorry that filetype is not supported, please see the image guidelines');
                    // cancel upload
                    return false;
                }
            },
            onSubmit: function(file, ext) {
                if (ext && /^(jpg|bmp|jpeg|gif)$/.test(ext)) {
                    /* Setting data */
                    button.addClass('uploadingBtn');
                    this.disable();
                    
                } else {
                
                    // extension is not allowed
                    alert('Sorry that filetype is not supported, please see the image guidelines');
                    // cancel upload
                    return false;
                }
                
            },
            onComplete: function(file, response) {
            
                button.removeClass('uploadingBtn');
                button.parent().parent().parent().find('label.error').css({
                    "display": "none"
                });
                // window.clearInterval(interval);
                
                // enable upload button
                this.enable();
                //console.log('response  ::  ' + response);
                var url = response.replace(/<\/?[^>]+>/gi, '');
                //console.log('url  ::  ' + url);
                // set image
                if (url != null && url.indexOf("/") > -1) {
                    $('#imgError').html("");
                    $('.regImage').css('height', "90px");
                    $('.regImage').css('width', "120px");
                    $('.regImage').attr('src', url);
                    $('.regImage').show();
                    $('#profileImage').val(url);
                } else {
                    $('#imgError').html(url);
                }
                
                
            }
        });
    },
    Registration: {
        getRegistrationForm: function() {
            $.getJSON('/ContentModuleService.svc/GetRegistrationFormHtml', function(data) {
                $('div.reqStage').html(data.Content);
                $('div.reqStage>div.innerRegistrationWrapper[jsClass]').each(function() {
                    $.getScript('js/' + $(this).attr('jsClass') + '.js');
                });
            });
        },
        doKeyStonRegistration: function() {
            Amnesia.Request.addRequest(Amnesia.Request.SelectedRequest);
        },
        getPrivacyStatement: function(_node) {
            var _corporateContent;
            if ($(_node).text().toUpperCase() == "PRIVACY INFORMATION") {
                $.get('/Templates/Static/privacyStatements.htm', function(data) {
                    if ($(_node).parents('div#requestsWrapper').length > 0) {
                        _corporateContent = $(data).find('div.corp_Content');
                    } else {
                        _corporateContent = data
                    }
                    $('div#RequestPrivacyInformationPlaceHolder').html(_corporateContent);
                    $('div#RequestPrivacyInformationPlaceHolder').animate({
                        height: "show"
                    });
                    $(_node).text("Close Privacy information");
                });
                
            } else 
                if ($(_node).text().toUpperCase() == "CLOSE PRIVACY INFORMATION") {
                    $('div#RequestPrivacyInformationPlaceHolder').animate({
                        height: "hide"
                    });
                    $(_node).text("Privacy information");
                }
        },
        getTermsAndConditions: function(_node) {
            var _corporateContent;
            if ($(_node).text().toUpperCase() == "TERMS & CONDITIONS") {
                $.get('/Templates/Static/InteractiveTermsandConditions.htm', function(data) {
                
                    if ($(_node).parents('div#requestsWrapper').length > 0) {
                        _corporateContent = $(data).find('div.corp_Content');
                    } else {
                        _corporateContent = data
                    }
                    
                    $('div#RequestTermsAndCondition').html(_corporateContent);
                    $('div#RequestTermsAndCondition').animate({
                        height: "show"
                    });
                    $(_node).text("Close Terms & Conditions");
                    $('input#TACagree').eq(0).get(0).checked = true;
                });
                
            } else 
                if ($(_node).text().toUpperCase() == "CLOSE TERMS & CONDITIONS") {
                    $('div#RequestTermsAndCondition').animate({
                        height: "hide"
                    });
                    $(_node).text("Terms & Conditions");
                }
        }
    },
    Login: {
        getForgotPasswordForm: function() {
            $.get('/Templates/Login/PasswordReminderForm.html', function(data) {
                $('div.forgotPass').html(data);
                //$('div.reqStage').hide();
            });
        },
        doKeyStoneLogin: function(e, f) {
            $(e).doLogin(f);
        },
        sendRequestForPWRetrieval: function(_node) {
            var theEmail = ($(_node).parents('ul.formList').eq(0).find('li.ForgotPasswordMsg input#ResendPasswordEmail').eq(0).val());
            
            $.ajax({
                type: "POST",
                url: "/UserAccountService.svc/ResendPassword",
                data: '{"emailAddress":"' + theEmail + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(result) {
                    //result.d.WasSent = true;
                    if (!result.d.WasSent) {
                        $('.Err1').css('display', 'none');
                        $('.Err2').css('display', 'none');
                        $('.EmailNotFound').css('display', 'block');
                    } else {
                        $('.EmailNotFound').css('display', 'none');
                        $('.ForgotPasswordMsg').css('display', 'none');
                        $('.ForgotPasswordSentConfirmation').css('display', 'block');
                    }
                    
                }
            });
        }
        
    }
};


// Tooltip
(function($) {
    $.fn.ttshow = function(_option) {
        switch (_option) {
            case "request":
                var _node = $(this).get(0);
                $(_node).addClass("hoverLi");
                if ($(_node).attr('class').indexOf('showPop') >= 0) {
                    return;
                } else {
                    _node.timeoutID = window.setTimeout(Amnesia.Request.RequestToolTipTimeOutSetter(_node), 1000);
                }
                break;
            case "imgGuideLine":
                
                var _ttContent = {};
                _ttContent.PlaceHolder = $(this).parents('label').eq(0).nextAll('div.ttcontentPlaceHolder').eq(0).get(0);
                _ttContent.element = $(_ttContent.PlaceHolder).find('div.ttcontents').eq(0).get(0);
                var instructions = $(this).GetChVToolTipInstruction();
                var thePos = $.util.getAbsolutePageXYPosition($(this).get(0));
                //pass the position value - this is inconsistent with login, we need to sort this out when all requirements on the tooltip get revealed
                instructions.top = thePos.y - $(_ttContent.element).height() - 10;
                instructions.left = thePos.x;
                $($.TTContentMgr.DOM).ShowToolTip(_ttContent, instructions);
                
                if (dd.ie) {
                    $.tooltip.SetToolTipWidthOnIE($(_ttContent.element).width());
                }
                
                //override the position value
                $($.TTContentMgr.DOM).css({
                    'top': (thePos.y - $('#xbcontent').height() - 20) + "px",
                    'left': instructions.left + "px"
                });
                
                break;
                
                
            case "pgGuideShow":
                
                var _ttContent = {};
                _ttContent.PlaceHolder = $(this).find('.tvgToolTipPlaceholder').eq(0).get(0);
                _ttContent.element = $(_ttContent.PlaceHolder).find('.tvgToolTip').eq(0).get(0);
                var instructions = $(this).GetChVToolTipInstruction();
                var thePos = $.util.getAbsolutePageXYPosition($(this).get(0));
                
                //pass the position value - this is inconsistent with login, we need to sort this out when all requirements on the tooltip get revealed
                instructions.top = thePos.y - $(_ttContent.element).height();
                instructions.left = thePos.x;
                $($.TTContentMgr.DOM).ShowToolTip(_ttContent, instructions);
                
                if (dd.ie) {
                    $.tooltip.SetToolTipWidthOnIE($('.tvgToolTip').width());
                }
                
                
                //override the position value
                $($.TTContentMgr.DOM).css({
                    'top': (thePos.y - $('#xbcontent').height() - 20) + "px",
                    'left': instructions.left + "px"
                });
                
                break;
        }
        
    };
    
    $.fn.tthide = function(_option) {
        switch (_option) {
            case "request":
                var _node = $(this).get(0);
                window.clearTimeout(_node.timeoutID);
                _node.timeoutID = null;
                $(_node).removeClass("hoverLi");
                $(_node).removeClass('showPop');
                break;
            case "imgGuideLine":
                $(this).CloseToolTip();
                break;
                
            case "pgGuideShow":
                $(this).CloseToolTip();
                break;
        }
        
    };
})(jQuery)

/* ++++ TABS +++*/
$(function() {
    $.fn.amnesiaTabs = function(_arg) {
    
    
        var _node = _arg;
        var argType = (typeof _node).toUpperCase();
        var ulElement, ulObj;
        switch (argType) {
            case 'UNDEFINED':
                ulElement = $('#tabs').find('ul').eq(0);
                break;
                
            case 'STRING':
                ulElement = $('#' + _node).find('ul').eq(0);
                break;
                
            case 'OBJECT':
                ulElement = $(_node).find('ul').eq(0);
                break;
                
            default:
                break;
        }
        
        var panels = [];
        
        $(ulElement).nextAll().css("display", "none");
        $(ulElement).find('[href]').each(function() {
            var idvalue = this.getAttribute('href');
            if ($.browser.msie) {
                idvalue = (idvalue.substring(idvalue.indexOf('#'), idvalue.length));
            }
            
            panels[panels.length] = idvalue;
            $(this).bind('click', function(e) {
                $(this).parent().siblings().removeClass("set");
                $(this).parent().addClass('set');
                
                for (var i = 0; i < panels.length; i++) {
                    if (panels[i] != idvalue) {
                        $(panels[i]).css('display', 'none');
                    }
                }
                $(idvalue).css('display', 'block');
                return false;
            });
        })
        
        
        $(ulElement).data('members', panels);
        $($(ulElement).data('members')[0]).css('display', 'block');
        
    }
});

/* +++++ SCROLLER ++++*/

$(document).ready(function() {
    var _FirstTickerLi = 0;
    var _FirstTickerLiW = 0;
    var _SpeedTicker = 2000;
    var _PauseTicker = 8000; //leave song displayed for 8 seconds
    _PauseRefreshTicker = 18000000; // refresh ticker every 5 minutes
    _IntervalTicker = "";
    
    getTickerContent();
    _RefreshTicker = setInterval(getTickerContent, _PauseRefreshTicker);
    
    $('ul#CHVticker').hover(function() {
        clearTimeout(_IntervalTicker);
    }, function() {
        _IntervalTicker = setInterval(removeFirstTickerLi, _PauseTicker);
    });
});

function removeFirstTickerLi() {
    var _SpeedTicker = 2000;
    var _FirstTickerLi = $('ul#CHVticker li:first').html();
    var _TickerLiW = $('ul#CHVticker').width();
    var j, k;
    _LIs = $('ul#CHVticker li');
    j = $('ul#CHVticker').get(0).theLI;
    if (j == _LIs.length - 1) 
        k = 0;
    else 
        k = j + 1;
    
    _LIs.eq(k).css({
        marginLeft: _TickerLiW + 5
    });
    _LIs.eq(j).animate({
        marginLeft: (-_TickerLiW - 30)
    }, _SpeedTicker);
    _LIs.eq(k).animate({
        marginLeft: 0
    }, _SpeedTicker);
    $('ul#CHVticker').get(0).theLI = k;
}

function getTickerContent() {
    clearTimeout(_IntervalTicker);
    $('ul#CHVticker').empty();
    $.ajax({
        type: "GET",
        url: "/LiveBroadcastFeedService.svc/GetRecentTracksForTicker",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            $(result.Tracks).each(function() {
                var _LI = '<li>' + this.BroadcastTimeString + ' - ' + this.ArtistName + ' : <span>' + this.TrackName + '</span>';
                if (this.BuyNowUrl != "") _LI += ' &nbsp;<a href="' + this.BuyNowUrl + '" target="_blank" class="TickerBuyNow"><span>BUY NOW</span></a>';
                _LI += '</li>';
                $('ul#CHVticker').append(_LI);
            });
            $('ul#CHVticker').get(0).theLI = 0;
            _SpeedTicker = 2000;
            _PauseTicker = 8000;
            $('ul#CHVticker li:first').css({
                marginLeft: 0
            });
            _IntervalTicker = setInterval(removeFirstTickerLi, _PauseTicker);
        }
    });
}

function faqscroll(faqnumber) {
    $.scrollTo('#faq' + faqnumber, 800);
}

function privscroll(privnumber) {
    $.scrollTo('#priv' + privnumber, 800);
}

function appendCSS(css_href) {
    var str = "head link[href='" + css_href + "']";
    if ($(str).length == 0) {
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", css_href);
        document.getElementsByTagName("head")[0].appendChild(fileref);
    }
}

function appendStyleToHead(id, Css) {
	var cssCount = 0;
	var idx = getArrayIndex(channelv.Page.customStylesIds, id);
	idx= -1;
	
	for (var i = 0; i < channelv.Page.customStylesIds.length; i++) {
        if (channelv.Page.customStylesIds[i] == id) idx=i;;
    }
	var hash = "#"+id;
	var stylesStr = "";
	if (idx> -1){
		$(hash).addClass("cS"+idx);
	}
	else {
		cssCount = channelv.Page.customStylesIds.length;
		channelv.Page.customStylesIds[cssCount] = id;
		var ClassName0 = "cS"+cssCount;
		ClassName =" ."+ClassName0;
		cssCount++;
		newCss = Css.replace(hash, ClassName);
		while(newCss.indexOf(hash) > 0){
			newCss = newCss.replace(hash, ClassName);
		}
		stylesStr = '<style rel="stylesheet"  type="text/css" media="all"> ';
		stylesStr += " \n " + newCss  ;
		stylesStr += '</style>';
		$("head").append(stylesStr);
		$(hash).addClass(ClassName0)
	}
}

function appendCustomStageStyleToHead(id, Url, Grad, Repeat, Clr) {
    var str = "head style[title*='customStageBackgrounds']";
		var stylesStr = "";
		stylesStr = '<style rel="stylesheet" title="customStageBackgrounds" type="text/css" media="all"> ';
								
		if (Url!='')	{
			stylesStr += '.customStage {background: transparent url(' + Url + ') no-repeat scroll center top !important;} ';
		 }
       
		if (Grad=='' && Clr!='')	{
			stylesStr += ' .customBgrDC {background-color:' + Clr + ';} ';
		}
		if (Grad!='' && Clr!='')	{
			stylesStr += ' .customBgrDC {background: '+Clr+' url(' + Grad + ') ' + Repeat + ' scroll center top !important;} ';
		}
		if (Grad!='' && Clr=='') {
			stylesStr += ' .customBgrDC {background: transparent url(' + Grad + ') ' + Repeat + ' scroll center top !important;}  ';
		}
		stylesStr +='  </style>'
		$("head").append(stylesStr);
}

function delayedCalls() {
    setTimeout(function() {
        appendCSS('/css/stylesOnAir.css');
        appendCSS('/css/stylesPresenterSearch.css');
        appendCSS('/css/stylesOzArtists.css');
        appendCSS('/css/stylesGigGuide.css');
    }, 15000)
    
}

function scrollToKeystone() {
    $.scrollTo('#keystoneMarker', 800);
    return true
}


function isObjEmpty(obj) {
    for (var i in obj) {
        return false;
    }
    return true;
}

function getArrayIndex(arr, cell) {
    for (i = 0; i < arr.length; i++) {
        if (arr[i] == cell) return i;
    }
    return -1
}

Amnesia.getTime = function(zone, callback) {
    Amnesia.gotTime = (!callback) ? Amnesia._gotTime : callback;
    var url = 'http://json-time.appspot.com/time.json?tz=' +
    zone +
    '&callback=Amnesia.gotTime';
    $.getScript(url);
};

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/, "");
}



Amnesia._gotTime = function() {
    console.log('no callback passed to Amnesia.getTime');
};
Amnesia.gotTime = Amnesia._gotTime;

(function($) {

    $.fn.sort = function(sortAttr, sortDesc) {
        //Must Specify Sort Attribute
        if (typeof(sortAttr) === "undefined") {
            return $(this);
        }
        if (sortAttr == "") {
            return $(this);
        }
        
        //If sort attribute is a single string such as "name"
        if (typeof(sortAttr) === "string") {
        
            var retObj = $(this).get().sort(function(a, b) {
                //Sort numeric values
                if (typeof($(a).attr(sortAttr)) === "number") {
                
                    return parseInt($(a).attr(sortAttr)) > parseInt($(b).attr(sortAttr)) ? 1 : -1;
                } //sort string values
 else {
                    return $(a).attr(sortAttr).toLowerCase() > $(b).attr(sortAttr).toLowerCase() ? 1 : -1;
                }
            });
            //If sort is descending
            if (getSort(sortDesc)) {
                return $(retObj.reverse());
            } else {
                return $(retObj);
            }
        }
        //If data is an object such as a returned JSON object
        if (typeof(sortAttr) === "object") {
            //If the sort attribute is an Array  i.e. ["Name", "Phone","Foo"] , this will sort based on that order.
            if ((sortAttr).length) {
                var retObj = $(this).get().sort(function(a, b) {
                    var i = 0;
                    var retval = 1;
                    while (i < sortAttr.length) {
                        var al = $(a).attr(sortAttr[i]).toLowerCase();
                        var bl = $(b).attr(sortAttr[i]).toLowerCase();
                        
                        if (al > bl) {
                            retval = 1;
                            break;
                        }
                        if (bl > al) {
                            retval = -1;
                            break;
                        }
                        i++;
                    }
                    return retval;
                    
                });
                if (getSort(sortDesc)) {
                    return $(retObj.reverse());
                } else {
                    return $(retObj);
                }
            } //Sort object based on single sort attribute
 else {
                var retObj = $(this).get().sort(function(a, b) {
                    var attrLen = 0;
                    for (var v in sortAttr) {
                        var al = $(a).attr(v).toLowerCase();
                        var bl = $(b).attr(v).toLowerCase();
                        if (al > bl) {
                            return (getSort(sortAttr[v])) ? -1 : 1;
                        }
                        if (bl > al) {
                            return (getSort(sortAttr[v])) ? 1 : -1;
                        }
                    }
                    
                });
                if (getSort(sortDesc)) {
                    return $(retObj.reverse());
                } else {
                    return $(retObj);
                }
                
            }
        }
    }
    
    //Determines if the sort should be Ascending(false) or Descending(true)
    //Can determine based on Boolean Value or String
    function getSort(sortDesc) {
        if (typeof sortDesc == "boolean") {
            return sortDesc;
        } else 
            if (sortDesc.toLowerCase() == "desc") {
                return true;
            } //Incase boolean value gets passed as string
 else 
                if (sortDesc.toLowerCase() == "true") {
                    return true;
                } else 
                    return false;
    }
})(jQuery);


