﻿/// <reference path="libs/jquery-1.3.2-vsdoc.js" />

/**
*	Javascript Tools based on jquery
*/
var amg = {};

$(function() { amg.init(); });

(function() {
    amg = {

        init: function() {
            // Standards compliant target = "_blank"
            $('a[rel="external"]').click(amg.utility.relExternal);
            $('a[rel="newMinWindow"]').click(amg.utility.newMinWindow);
            // hide default text in input boxes by clicking on it
            amg.utility.hidingTextInInputBoxes();
        },

        // General functions
        utility: {
            relExternal: function() {
                window.open(this.href);
                return false;
            },
            newMinWindow: function() {
                window.open(this.href, 'NewWindow', 'toolbar=0,status=0,location=0,menubar=0,directories=0,resizable=1,scrollbars=1');
                return false;
            },
            hidingTextInInputBoxes: function() {
                /*
                *  check all input[type=text] elements,
                *  remember default value
                *  make onFocus, onBlur functions
                *  // make focus on first found input
                *
                *  JUST FOR SEARCH INPUT
                */
                $("input[type=text]#q").focus(function() {
                    if (this.defVal == null) {
                        this.defVal = $(this).val();
                    }
                    if (this.value == this.defVal) {
                        this.value = "";
                    }
                });
                $("input[type=text]#q").blur(function() {
                    if (this.value == "") {
                        this.value = this.defVal;
                    }
                });
            }
        },

        // Home
        homeLanding: {

            init: function() {
                amg.homeLanding.heroPlayer();
                amg.calendar.init();
            },

            heroPlayer: function() {
                /* HERO PLAYER */
                if ($('#hero').size()) {
                    $('#hero li:not(.active)').css({
                        display: 'block',
                        opacity: 0
                    });

                    var heroPlayerHeight = $('#hero ul').height();
                    $('#hero ul li').each(function() {
                        var h = $('.text', $(this)).height() + $('h2', $(this)).height() + 50;
                        if (h > heroPlayerHeight)
                            heroPlayerHeight = h;
                    });
                    $('#hero ul').animate({ height: heroPlayerHeight });
                    $('#hero ul li').css('height', heroPlayerHeight);

                    var actualHeroPage = 1;
                    var autoplay = true;

                    if ($('#hero li').size()) {
                        $('#hero .nav').show();
                        $('#hero .nav div').text(actualHeroPage + '/' + $('#hero li').size());
                    }
                    $('#hero .nav .left').click(function() {
                        if ($('#hero li:animated').size())
                            return false;
                        //if((actualHeroPage <= 1) || ($('#hero li:animated').size()))
                        if (actualHeroPage <= 1) {
                            //return false;
                            actualHeroPage = $('#hero li').size() + 1;
                        }
                        actualHeroPage--;
                        $('#hero li').dequeue().stop();
                        $('#hero li.active').animate({
                            opacity: 0
                        }, 500);
                        $('#hero li').removeClass('active');
                        $('#hero li:eq(' + (actualHeroPage - 1) + ')').addClass('active');
                        $('#hero li.active').animate({
                            opacity: 1
                        }, 500);
                        $('#hero .nav div').text(actualHeroPage + '/' + $('#hero li').size());
                        return false;
                    });
                    $('#hero .nav .right').click(function() {
                        if ($('#hero li:animated').size())
                            return false;
                        if (actualHeroPage >= $('#hero li').size()) {
                            //return false;
                            actualHeroPage = 0;
                        }
                        actualHeroPage++;
                        $('#hero li').dequeue().stop();
                        $('#hero li.active').animate({
                            opacity: 0
                        }, 500);
                        $('#hero li').removeClass('active');
                        $('#hero li:eq(' + (actualHeroPage - 1) + ')').addClass('active');
                        $('#hero li.active').animate({
                            opacity: 1
                        }, 500);
                        $('#hero .nav div').text(actualHeroPage + '/' + $('#hero li').size());
                        return false;
                    });

                    function heroPlayerAutoplay() {
                        if (autoplay) {
                            $('#hero li').dequeue().stop();
                            var old = actualHeroPage;
                            actualHeroPage++;
                            if (actualHeroPage > $('#hero li').size())
                                actualHeroPage = 1;
                            $('#hero li').removeClass('active');
                            $('#hero li:eq(' + (actualHeroPage - 1) + ')').addClass('active');

                            $('#hero li:eq(' + (old - 1) + ')').animate({
                                opacity: 0
                            }, 400);
                            $('#hero li.active').animate({
                                opacity: 1
                            }, 400);

                            $('#hero .nav div').text(actualHeroPage + '/' + $('#hero li').size());
                        }
                    }
                    // timing, refresh in 5 seconds
                    HeroPLyaerTimeout = 5000;

                    // if there is more than 1 iteim in hero player than start it
                    // start delay while all page is loaded + time for facebook component
                    if ($('#hero li').size() > 1)
                        setTimeout(function() {
                            document.HeroPlayerTimer = setInterval(heroPlayerAutoplay, HeroPLyaerTimeout);
                        }, 2000);

                    $('#hero').hover(function() {
                        if (document.HeroPlayerTimer) {
                            clearInterval(document.HeroPlayerTimer);
                            document.HeroPlayerTimer = null;
                        }
                        autoplay = false;
                    }, function() {
                        if ($('#hero li').size() > 1) {
                            clearInterval(document.HeroPlayerTimer);
                            document.HeroPlayerTimer = setInterval(heroPlayerAutoplay, HeroPLyaerTimeout);
                        }
                        autoplay = true;
                    });
                }
            }
        },

        // Calendar
        calendar: {
            init: function() {
                /* CALENDAR popup */
                $('.eventViewCalendar tbody td .event-link').each(function() {
                    var link = $('.popup-link:first', $(this));
                    var popup = $('.popup:first', $(this)).css('opacity', 0);

                    link.mouseover(amg.calendar.popupLinkMouseOver).mouseout(amg.calendar.popupLinkMouseOut);
                    popup.mouseover(amg.calendar.popupLinkMouseOver).mouseout(amg.calendar.popupLinkMouseOut);
                });

                $('.calendarNavigation a').click(amg.calendar.ajaxInsert);
            },
            ajaxInsert: function() {
                var qs = new QueryString(this.href);
                var year = qs.get('year');
                var month = qs.get('month');
                var url = '/event/calendars?year=' + year + '&month=' + month;
                $.get(url, function(html) {
                    $('#calendar').replaceWith(html);
                    amg.calendar.init();
                });
                return false;
            },
            popupLinkMouseOver: function() {
                var parent = $(this).parent().get(0);
                var popup = $('.popup', parent);

                if (parent.hideDelayTimer)
                    clearTimeout(parent.hideDelayTimer);

                // if its acutally animating than dont animate again
                if ($('.popup:animated', parent).size())
                    return false;

                // if its showen than dont show again
                if ($('.popup:visible', parent).size())
                    return false;

                $(popup).css({
                    display: 'block',
                    top: -(popup.height() + 20)
                }).animate({
                    top: '-=10px',
                    opacity: 1
                }, 200);

                return false;
            },
            popupLinkMouseOut: function() {
                var parent = $(this).parent().get(0); ;
                var popup = $('.popup', parent);

                if (parent.hideDelayTimer)
                    clearTimeout(parent.hideDelayTimer);

                var actualIndex = $('.eventViewCalendar tbody td .event-link .popup').index(popup);

                // hide all other popups what 		// :animated - are not actualy animating (means they are hiding)
                $('.eventViewCalendar tbody td .event-link .popup:not(:eq(' + actualIndex + '))').css('opacity', 0);

                parent.hideDelayTimer = setTimeout(function() {
                    popup.animate({
                        top: '-=10px',
                        opacity: 0
                    }, 200, function() {
                        popup.css('display', 'none');
                    });
                }, 300);

                return false;
            }
        },

        Nickname: {
        	init: function() {
        		//ln.Registration.hints();
        		$('#Nickname').blur(amg.Registration.checkNickname);
        	}
        },
        
        Registration: {
            init: function() {
           },

           checkNickname: function() {
           	if (($('#Nickname').val() != "") && (document.Nickname != $('#Nickname').val())) {
           		document.Nickname = $('#Nickname').val();
           		$.getJSON('/Account/NicknameExists?nickname=' + $('#Nickname').val(), function(result) {
           			if (!result.length == 0) {
           				$("#jsNickname").html("");
           				if ($("#jsNickname .nickname-exists").size() == 0) {
           					$("#jsNickname").append("<span class=\"field-validation-error\ nickname-exists\">" + result + "</span>");
           				}
           			} else {
           				$(".nickname-exists").remove();
           			}
           		});
           	}
           },

            login: function() {
                amg.Registration.init();

                //$('form#registration input:first').focus();

                RegisterValue = $('#RegisterButton').text();
                SignInValue = $('#registration input[type=submit]').val();
                amg.Registration.loginShowHidePassword();

                $('form#registration input[type=radio]').click(function() {
                    amg.Registration.loginShowHidePassword();
                });
                $('#registration #Password').click(function() {
                    return false;
                });
            },

            edit: function() {
                amg.Registration.init();
                amg.Registration.DateCheck();

                //$('form#registration input:first').focus();
            },

            stepTwo: function() {
                amg.Registration.init();

                //$('form#registration input:eq(1)').focus();
            },

            stepThree: function() {
                amg.Registration.init();
                amg.Registration.DateCheck();
                $('#Nickname').blur(amg.Registration.checkNickname);
                amg.Registration.checkNickname();
                //$('form#registration input:eq(0)').focus();
            },

            changeEmail: function() {
                amg.Registration.init();
            },

            loginShowHidePassword: function() {
                if ($('input[name=IsAccountHolder]:checked').val() == "True") {
                    $('#registration input[type=submit]').val(SignInValue);
                    $('#registration #Password').show();
                    $('#registration .RememberMe').show();
                    $('#registration #RememberMe').show();
                    $('#hidePasswordError').show();
                } else {
                    $('#registration input[type=submit]').val(RegisterValue);
                    $('#registration #Password').hide();
                    $('#registration .RememberMe').hide();
                    $('#registration #RememberMe').hide();
                    $('#hidePasswordError').hide();
                }
            },

            DateCheck: function() {
                $('#Month').change(function() {
                    var y = $('#Year').val();
                    var m = $('#Month').val();
                    // disable submit
                    $('#registration input[type=submit]').attr('disabled', true);
                    $.get('/Account/GetDays?year=' + y + '&month=' + m, function(data) {
                        var o = $('#Day');
                        data = data * 1;
                        var dayvalue = o.val();
                        if (dayvalue > data * 1) {
                            dayvalue = 1;
                        }
                        amg.Registration.RegenerateDays(data);
                        o.val(dayvalue);
                        // enabled submit
                        $('#registration input[type=submit]').removeAttr('disabled');
                    });
                });
            },

            RegenerateDays: function(days) {
                var o = $('#Day');
                var selected = o.val();
                o.html('');
                for (i = 1; i <= days; i++)
                    o.append('<option value=' + i + '>' + i + '</option>');
            }
        },
        
        unsubscribe: function() {
            $('form.subscriptionsForm input[type=checkbox]:not(#unsubscribe)').click(function() {
                $('#unsubscribe').attr('checked', false);
            });
            $('#unsubscribe').click(function() {
                if( $(this).attr('checked') )
                {
                    $('form.subscriptionsForm input[type=checkbox]:not(#unsubscribe)').attr('checked', false);
                }
            });

        }

    }; // End of namespace

    // Classes
    // http://adamv.com/dev/javascript/files/querystring.js
    function QueryString(qs) { // optionally pass a querystring to parse
        this.params = {};

        if (qs == null) qs = location.search.substring(1, location.search.length);
        if (qs.length == 0) return;

        var hashIndex = qs.indexOf('#');
        if (hashIndex != -1)
            qs = qs.substring(0, hashIndex);

        // Turn <plus> back to <space>
        // See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
        qs = qs.replace(/\+/g, ' ');
        var args = qs.split('&'); // parse out name/value pairs separated via &

        // split out each name=value pair
        for (var i = 0; i < args.length; i++) {
            var pair = args[i].split('=');
            var name = decodeURIComponent(pair[0]);

            var value = (pair.length == 2)
			? decodeURIComponent(pair[1])
			: name;

            this.params[name] = value;
        }
    }

    QueryString.prototype.get = function(key, default_) {
        var value = this.params[key];
        return (value != null) ? value : default_;
    }

    QueryString.prototype.contains = function(key) {
        var value = this.params[key];
        return (value != null);
    }

})();



/* LASTFM PLAYER */
/* Still need to update the player with O2 Key */
function playStation() {
	playUrl("playlist/5443391/shuffle");
}
function playUrl(url) {
	window.open("http://www.last.fm/lastfminabox/popup?key=826c121615b9693e09a625470fed9162&station=" + url, 
                "lastFmInABoxPlayer", 
                "menubar=no,scrollbars=yes,width=750,height=600,toolbar=no");
}