    $.UI = {
    	    play : $('#play'),
    		fwd : $('#frwd'),
    		back :  $('#back'),
    		volume : $('#volume'),
    		time : $('#totalTime'),
    		playlists : $('#bottomLeft'),
    		player : $('#player'),
    		position : $('#position')
    }
    
    $.temp = {};
    

$(document).ready(function(){
	
    player.playing = false;
    player.init();
    $('#seek').seek();
    if ($.browser.msie) $.fx.off = true;

    $.UI.fwd.click(function(){ player.next() });
    $.UI.back.click(function(){ player.back() });
    $.UI.play.click(function(){ if (player.playid) player.pause() });
    
	$.UI.volume.slider({
		slide : function(event, ui) {
			player.volume = ui.value;
			player.changeVolume();
		},
		min : 0,
		value : player.volume,
		max : 100,
		stop : function(event, ui) {
			cookie.createCookie('volume', ui.value, '90');
		}
	});

	$.UI.playlists.hover(function() {
		$(this).delay(100).animate({
			left : '0',
		}, 100, 'linear');
	}, function() {
		$(this).delay(300).animate({
			left : '-160',
		}, 500, 'linear');
	});

	$('a.inView').live('waypoint', function(event, direction) {
		var page = $(this).attr('href');
		$.ajax({
			url : '/navigator.php?q=' + page,
			success : function(data) {
				$.UI.player.append(data);
			}
		});
	});


	$.ajaxSetup({
		beforeSend : function() {
			$('body').css('cursor', 'progress');
			$('#loading').show();
		},
		complete : function(XMLHttpRequest, textStatus) {
			$('#temp').cleanup();
			$('body').css('cursor', 'default');
			$('#loading').hide();
			if($.temp.refresh) {
				player.currentTrack()
			};
			if(XMLHttpRequest) {
				var title = XMLHttpRequest.getResponseHeader("x-title");
				var mode = XMLHttpRequest.getResponseHeader("x-media_mode");
				var cache = XMLHttpRequest.getResponseHeader("x-cache-bol");
			}
			if($('html').hasClass('localstorage') && cache) {
				$.storage.write({
					key : document.location.hash,
					onError : function(e) {
						return false;
					},
					value : {
						data : escape($.trimWhiteSpace($.UI.player.html())),
						time : $.timeStamp()
					}
				});
			}
			$('#loading').hide();
			if(title) {
				document.title = 'igrooves | ' + title;
			}
			if(mode) {
				$('#searchType > select').val(mode);
			}
			FB.XFBML.parse();
			gapi.plusone.render();
			igrooves.setUpUi();
		},
		data : {
			js : true,
			jsLoop : true
		}
	});

	$('form').live('submit', function(event) {
		try {
			var form = {};
			var result = null;
			form.elem = $(this);
			form.formVars = form.elem.getFormValues();
			form.action = form.elem.attr('action');
			form.method = form.elem.attr('method');
			form.fields = form.elem.find('input');
			form.fields.attr('disabled', 'true');
			$.formData = {};
			if(form.formVars.responseType == 'ajax') {
				$.ajax({
					type : 'POST',
					url : form.action,
					dataType : form.formVars.dataType,
					data : form.formVars,
					success : function(data) {
						var result = data;
						eval("" + form.formVars.handler + "");
					}
				});
			} else {
				eval("" + form.formVars.handler + "");
			}
			form.fields.removeAttr('disabled');
			return false;
		} catch(e) {
			console.log(e);
		}
		return false;
	});

	$('a').live('click', function(event) {
		if($(this).attr('href') && $(this).attr('href').indexOf('download.php') == -1) {
			if($(this).hasClass('nonav') || $(this).hasClass('login')) {
				if($(this).hasClass('addComment')) {
					igrooves.comment($(this).data('comment'));
					return false;
				}
				return false;
			} else {
				//if(typeof(history.pushState) == 'function') {
				//	history.pushState(false,false,$(this).attr('href').replace(/https?:\/\/[^\/]+/i, ""));
				///} else {
				document.location.hash = '#!' + $(this).attr('href').replace(/https?:\/\/[^\/]+/i, "");
				//}
				return false;
			}
		}
	});

    $('.dloadbutton').click(function(){
        $('#buyform').dialog('close');
    });
    
    $('div.song').live('click', function(event){
        var $target = $(event.target);
        if ($target.parent().hasClass('song') && !$target.parent().hasClass('playing')) {
            player.play($(this));
        }
    });

	$('ul.starRating li a').live('click', function(event) {
		var ul = $(this).parents('ul');
		if(ul.hasClass('rating')) {
			return false;
		}
		ul.addClass('rating');
		var data = $(this).parents('ul').data('rating');
		console.log($(this).data('num'));
		var _data = {
			rate_num : $(this).data('num'),
			mode : 'update_rating',
			template : 'json_rating.tpl',
			tpl_dir : 'skin',
			template_content_type : 'xml'
		};
		var param = $.extend(data, _data);
		$.ajax({
			url : 'rating.php',
			data : param,
			dataType : 'json',
			success : function(data) {
				var target = $('li.ratingResult.' + param.type + '-rating-' + param.id);
				var pc = $('li.currentRating.' + param.type + '-rating-' + param.id);
				console.log(pc);
				ul.removeClass('rating');
				if(data.error_id == "00") {
					var msg = $('<span/>').addClass('success').html('Rated ' + param.rate_num);
				} else {
					var msg = $('<span/>').addClass('failed').html('Already rated');
				}
				pc.each(function() {
					$(this).css('width', data.percent + '%');
				});
				target.append(msg).fadeOut(5000);
			}
		});

	});

	$('.buy, .donate').live('click', function() {
		var ops = $(this).data('buy');
		console.log(ops);
		$.rest.get.userInfo();
		if($.userInfo.loggedIn) {
			$.ajax({
				url : '/buy.php',
				data : ops,
				success : function(data) {
					$('#buyform').html(data).removeClass("hide").dialog({
						width : 530,
						position : 'center'
					});
				}
			});
		} else {
			$('#login-form').dialog({
				width : 500,
				position : 'center'
			});
			$.onlogin = function() {
				$.ajax({
					url : '/buy.php',
					data : ops,
					success : function(data) {
						$('#buyform').html(data).removeClass("hide").dialog({
							width : 530,
							position : 'center'
						});
					}
				});
			}
			$('#userName').focus();
		}
	});

    $(window).hashchange(function(){
        $(this).navigate();
    });
    
    $.historyOffset = $('#history > ul').offset().left;
    
    $('#history > ul').mousemove(function(e){
    		if($(this).width() < $(window).width()) return false;
			var x = e.pageX/($(window).width()-$.historyOffset);
			var left = Math.floor(($(this).width()-$(window).width()+50)*x);
			$(this).css('right',left);
	});
	
	$('#nowPlaying').addClass('inactive');

	$('#igrooves_trayicon_2').click(function() {
		$('#nowPlaying').fadeOut('fast');
		$('#queue').fadeOut('fast');
		$('#historyContainer').toggle(400);
	});
	$('#igrooves_trayicon_1').click(function() {
		if($('#queue_tab').hasClass('inactive'))
			return false;
		$('#nowPlaying').fadeOut('fast').removeClass('open');
		$('#historyContainer').fadeOut('fast');
		$('#queue').toggle(400);
	});
	$('#igrooves_trayicon_0').click(function() {
		if($('#nowPlaying_tab').hasClass('inactive'))
			return false;
		$('#historyContainer').fadeOut('fast');
		$('#queue').fadeOut('fast');
		clearTimeout($.animation_timeout);
		$.UI.player.css('padding-bottom', '130px');
		if($('#nowPlaying').hasClass('open')) {
			$.hideRoot();
		} else {
			$('#nowPlaying').show().animate({
				height : "170px"
			}, {
				duration : 300,
				specialEasing : {
					width : 'linear'
				}
			}).addClass('open');
		}
	});


    $(this).navigate();

	$('#loginLink, .login').live('click', function() {
		$('#login-form').dialog({
			width : 500,
			position : 'center'
		});
		$('#userName').focus();
		return false;
	});

	if( typeof (localStorage) != 'undefined' && $.storage.get("history")) {
		var html = '';
		var playhistory = $.parseJSON($.storage.get("history"));
		var i = 0;
		for(var key in playhistory) {
			if(playhistory[key] != 'undefined') {
				i++;
				html = html + playhistory[key];
			}
		}
		$('#history > ul.mouseslider > li.empty').remove();
		$('#history > ul.mouseslider').prepend(html).css('width', (i * 120) + 240 + 'px');
	}

	$(window).scroll(function() {
		if(document.documentElement.clientHeight + $(document).scrollTop() >= document.body.offsetHeight) {
			if($('a.inView').length > 0) {
				var url = $('a.inView:first').attr('href');
				$('a.inView:first').remove();
				$.ajax({
					url : '/navigator.php?q=' + url,
					data : {
						noPager : true
					},
					success : function(data) {
						$.UI.player.append(data);
					}
				});
			}
		}
	});



}).keyup(function(e) {
	//console.log(e.target,e.which);
	if(!$(e.target).is('input, textarea')) {
		switch (e.which) {
			case 27:
				//esc
				$('.esc').fadeOut('300');
				break;
			case 32:
				if(player.playid) {
					player.pause();
				}
				break;
			case 78:
				if($('#nowPlaying_tab').hasClass('inactive'))
					return false;
				$('#historyContainer').fadeOut('fast');
				$('#queue').fadeOut('fast');
				clearTimeout($.animation_timeout);
				$.UI.player.css('padding-bottom', '130px');
				if($('#nowPlaying').hasClass('open')) {
					$.hideRoot();
				} else {
					$('#nowPlaying').show().animate({
						height : "170px"
					}, {
						duration : 300,
						specialEasing : {
							width : 'linear'
						}
					}).addClass('open');
				}
				break;
		}
	}
});


var player = {
    sm: soundManager,
    seeklock: false,
    volume: 80,
    repeat: false,
    today: new Date(),
    infoSent: false,
    init: function(){
        this.sm.debugMode = false;
        this.sm.consoleOnly = true;
        this.sm.url = '/jsf/sm/';
        this.sm.allowPolling = true;
        this.sm.flashLoadTimeout = 1000;
        this.sm.flashVersion = 9;
        this.sm.nullURL = 'null.mp3';
        this.sm.useMovieStar = false;
        this.sm.onload = function () {
        		$.playerReady = true;
        };
		if ($.browser.msie) {
            this.sm.useFastPolling = false;
            this.sm.useHighPerformance = false;
        }
        else {
            this.sm.useFastPolling = true;
            this.sm.useHighPerformance = true;
        };
        this.sm.waitForWindowLoad = true;
        this.setVolume();
        this.media = {
            bytes: null,
            bitrate: null
        };
        	//this.sm.useHTML5Audio = true;
        //this.sm.ignoreFlash = true;
    },
    fi: 'song_lofi',
    setVolume: function(){
        if (cookie.readCookie('volume')) {
            this.volume = cookie.readCookie('volume');
            $.UI.volume.slider('option', 'value', this.volume);
        }
        else {
            this.volume = '80';
        }
    },
    seconds: '00:00',
    Time : $('#_Time'),
    Loaded : $('#seekLoadedMask'),
    Position  : $('#seekMask'),
    playTrack: function(){
        if (this.sid == this.Nid || this.lock) {
            return false;
        }
        this.stop();
        this.playid = 'song' + this.sid;
        this.track = this.sm.createSound({
            id: this.playid,
            volume: this.volume,
            url: 'http://igrooves.net:81/stream.php?u=&mode=' + this.fi + '&band_id=' + this.bid + '&song_id=' + this.sid,
            whileplaying: function(){
            		var nSec = Math.floor(this.position / 1000);
                var Min = Math.floor(nSec / 60);
                var sec = nSec - (Min * 60);
                
				var pc = new Number((this.position / player.secbitbyte * 100)).toFixed(2)+'%';
            		player.Loaded.css('width',pc);
            		$.UI.position.text(Min + ':' + (sec < 10 ? '0' + sec : sec));
            },
            whileloading: function(){
            		var pc = (this.bytesLoaded / player.media.bytes) * 100 + '%';
                player.Position.css('width',pc);
            },
            onplay: function(){
                $.UI.play.addClass('pause');
                player.togglePlay();
                player.infoSent = false;
            },
            onpause: function(){
                $.UI.play.removeClass('pause');
            },
            onresume: function(){
                $.UI.play.addClass('pause');
            },
            onstop: function(){
                $.UI.play.removeClass('pause');
                $('#nowPlaying').empty().addClass('inactive').fadeOut(500);
                player.infoSent = false;
            },
            onfinish: function(){
                $.temp.songData = false;
                $.UI.play.removeClass('pause');
                if (player.repeat) {
                    this.setPosition(player.playid, 0);
                    this.play();
                }
                else {
                    player.stop();
                    player.next();
                }
                $('#nowPlaying').empty().addClass('inactive').fadeOut(500);
            }
        });
        this.track.play();
        this.histSet = false;
        var today = this.today.format('d-m-y');
        var obj = this;
        this.track.onposition(2000, function(){
			if(!player.infoSent){ 
				$.rest.get.songInfo(player.sid);
       			player.infoSent = true;
       		}
            var history = $.parseJSON($.storage.get("history"));
            if (!history) {
                var history = {};
            }
            var html = '<li id="history-' + $.temp.trackdata.song_id + '"><img width="100" height="100" alt="' + $.temp.trackdata.song_name + '" src="http://song.static.igm.me/mediaimage/song_image/' + $.temp.trackdata.band_id + '/' + $.temp.trackdata.song_id + '/100/100/image.png">' +
            '<a href="/music/focus/' +
            $.temp.trackdata.song_id +
            '/' +
            $.temp.trackdata.song_name +
            '">' +
            $.temp.trackdata.song_name +
            '</a>' +
            '<a href="' +
            document.location.hash.substr() +
            '">Results page</a>' +
            '</li>';
            if (!history[$.temp.trackdata.song_id]) {
                var width = $('#history > ul.mouseslider').width()
                $('#history > ul.mouseslider > li.empty').remove();
                $('#history > ul.mouseslider').prepend(html).css('width', width + 130 + 'px');
                history[$.temp.trackdata.song_id] = html;
                history = JSON.stringify(history);
                $.storage.write({
                    key: "history",
                    value: history
                });
            }
            else {
                delete history[$.temp.trackdata.song_id];
                history[$.temp.trackdata.song_id] = html;
                $.storage.write({
                    key: "history",
                    value: JSON.stringify(history)
                });
                $('#history-' + $.temp.trackdata.song_id).remove();
                $('#history > ul.mouseslider').prepend(html);
            }
        });
    },
    stop: function(){
        if (this.playid) {
            this.sm.stopAll();
            this.sm.destroySound(this.playid);
        }
        $('#nowPlaying').addClass('inactive');
    },
    back: function(){
        if ($('#player > .song:first').attr('id') != $('.playing').attr('id')) {
        		this.play($('div.song.playing').prev('div.song'));
        }
        else {
            this.play($('#player > div.song:last'));
            $('body').animate({
                scrollTop: $('body')[0].scrollHeight
            }, 'slow');
        }
    },
    next: function(){
        if ($('#player > .song:last').attr('id') != $('.playing').attr('id')) {
            this.play($('div.song.playing').next('div.song'));
        }
        else {
            this.play($('#player > div.song:first'));
            $('body').animate({
                scrollTop: 0
            }, 'slow');
        }
    },
    pause: function(){
        this.sm.togglePause(this.playid);
    },
    play: function(obj){
        var sd = obj.data('song');
        $('.playing').removeClass('playing');
        obj.addClass('playing');
        this.media.bitrate = sd.lofi_bitrate * 128;
        this.media.bytes = sd.lofi_size;
        this.media.length = sd.totalseconds*1000;
        this.secbitbyte = (this.media.bytes / this.media.bitrate) * 1000;
        this.total = ((this.media.bytes / this.media.bitrate) * 1.021341) * 1000;
        this.sid = sd.song_id;
        this.bid = sd.band_id;
        this.playTrack();
        this.playing = true;
        $.temp.trackdata = obj.data('song');
        $.UI.time.html(sd.lofi_length);
    },
    togglePlay: function(){
        return true;
    },
    seek: function(){
        this.media.track.position;
        this.media.track.bytesLoaded;
    },
    changeVolume: function(){
        if (this.playid) {
            this.sm.setVolume(this.playid, this.volume);
        }
    },
    currentTrack: function(){
        var id = $('#' + this.sid);
        $('.playing').removeClass('playing');
        id.addClass('playing');
    }
};
var igrooves = {
    signup: function(data){
        $.UI.player.empty().html(data);
    },
    userdata: function(){
        return igrooves.rest.send({
            mode: 'userdata'
        });
    },
    rest: {
        jsonVal: function(param){
            var result;
            $.ajax({
                url: '/restserver.php?mode=signupValidate&type=' + param.type + '&q=' + param.q,
                dataType: 'json',
                async: false,
                complete: function(data){
                    result = data;
                    $('body').css('cursor', 'default');
                    $('#loading').hide();
                }
            });
            var output = $.parseJSON(result.responseText);
            return output;
        },
        send: function(param){
            var result;
            if (!param.url) {
                param.url = '/restserver.php';
            }
            $.ajax({
                url: param.url,
                dataType: 'json',
                data: param,
                async: false,
                complete: function(data){
                    result = data;
                    $('body').css('cursor', 'default');
                    $('#loading').hide();
                }
            });
            var output = $.parseJSON(result.responseText);
            return output;
        }
    },
    setUpUi: function(){
    	console.log('uisetup fired')
        $('div.songName').draggable({
            cursor: "move",
            cursorAt: {
                top: 0,
                left: -10
            },
            helper: function(event){
                return $("<div id=\"ui-help\" data-id=\"" + $(this).parent().data('id') + "\" class='ui-widget-header'>Drop me over a playlist to add \"" + $(this).html() + "\"</div>");
            },
            start: function(){
                $('div#playlists > ul').addClass('draging');
                $('#advise').fadeOut('fast');
                $.UI.playlists.delay(100).animate({
				    left: '0',
				  }, 100,'linear');
            },
            stop: function(){
                $('div#playlists > ul').removeClass('draging');
                $.UI.playlists.delay(300).animate({
				    left: '-120',
				  }, 500,'linear');
            }
        }).bind('onselectstart',function () {return false;});
        $('li.userPlaylists').droppable({
        		drop : function (e, ui) {
        			console.log(event,ui);
        		}
        });
    },
    login: function(params){
        params.elem.children().attr('disabled', 'disabled');
        $('#error').text("Please wait...");
        $.ajax({
            url: params.action,
            data: params.formVars,
            success: function(data){
                data = $.parseJSON(data);
                console.log(data);
                if (data.error == '01') {
                    $('#error').text(data.errormessage);
                    params.elem.children().attr('disabled', '');
                    $('#password').val('').focus();
                }
                else {
                		$.rest.get.userInfo();
                    igrooves.loadUserData(data);
                    if($.onlogin) {
                    		$.onlogin.call();
                    }
                }
            }
        });
    },
    buy: function(html){
        $('#buyform').html(html).removeClass("hide").dialog({
            width: 530,
						position : 'center'
        });
    },
    loadUserData: function(data){
        $("#login-form").dialog('close');
        $('div#playlists a.login').remove();
        $('div#playlists > ul').append(data.playlists);
        $('#right > ul.menuRight').empty().html(data.html);
    },
    comment: function(data){
        var loggedin = userdata();
        if (loggedin.data.user_id) {
            $('.addComment').hide();
            $('#comment_form').fadeIn('fast');
            $('div.commentEntries').addClass('shrink');
            $('#comment_form > input.cancel').click(function(){
                $('div.commentEntries').removeClass('shrink');
                $('.addComment').show();
                $('#comment_form').fadeOut('fast');
                $('#commentEntries > div.comments > div.error').hide();
            });
        }
        else {
            $("#login-form").dialog("open");
        }
    },
    comment_save: function(form){
        
    }
};


var get = new APE.Client();

get.load();
get.addEvent('load', function() {
	this.core.start({
		"name" : String((new Date()).getTime()).replace(/\D/gi, '')
	});
});

get.addEvent('ready', function() {
	this.subscribed = {};
	if($.channels) this.core.join($.channels);
	this.addEvent('onRaw', function(e) {
		//console.log(e);
	});
	this.onRaw('CHANNEL', function(params) {
		console.log('join channel '+params.data.pipe.properties.name);
		this.subscribed[params.data.pipe.properties.name] = params.data.pipe.pubid;
	});
	this.onRaw('LEFT', function(params) {
		console.log('left channel '+params.data.pipe.properties.name);
		delete this.subscribed[params.data.pipe.properties.name];
	});
	this.onRaw('feed', function(params) {
		console.log('feed');
		console.log(params);
	});
	this.onRaw('audiofeed', function(params) {
		console.log('feed');
		console.log(params);
	});
	// this.onRaw('quickSearch', function (response) {
	// $.quickSearch.recieve(response);
	//});
	this.comments = function(id, type, limit) {
		this.core.request.send('comments', {
			'id' : id,
			'type' : type,
			'limit' : limit
		});
	}
	this.joinChannel = function(name) {
		this.core.join(name);
	}
	this.leaveChannel = function(name) {
		if(this.subscribed[name]) {
			this.core.left(this.subscribed[name]);
		}
	}
		
});


var cookie = {
    createCookie: function(name, value, days){
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else 
            var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/; domain=.igrooves.net";
    },
    readCookie: function(name){
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') 
                c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) 
                return c.substring(nameEQ.length, c.length);
        }
        return null;
    },
    eraseCookie: function(name){
        createCookie(name, "", -1);
    }
}
var search = function(options){
    document.location.hash = '#!' + options.q + options.string;
    return false;
}

Date.prototype.format = function(format){
    var returnStr = '';
    var replace = Date.replaceChars;
    for (var i = 0; i < format.length; i++) {
        var curChar = format.charAt(i);
        if (replace[curChar]) {
            returnStr += replace[curChar].call(this);
        }
        else {
            returnStr += curChar;
        }
    }
    return returnStr;
};
Date.replaceChars = {
    shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    longMonths: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
    longDays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
    d: function(){
        return (this.getDate() < 10 ? '0' : '') + this.getDate();
    },
    D: function(){
        return Date.replaceChars.shortDays[this.getDay()];
    },
    j: function(){
        return this.getDate();
    },
    l: function(){
        return Date.replaceChars.longDays[this.getDay()];
    },
    N: function(){
        return this.getDay() + 1;
    },
    S: function(){
        return (this.getDate() % 10 == 1 && this.getDate() != 11 ? 'st' : (this.getDate() % 10 == 2 && this.getDate() != 12 ? 'nd' : (this.getDate() % 10 == 3 && this.getDate() != 13 ? 'rd' : 'th')));
    },
    w: function(){
        return this.getDay();
    },
    z: function(){
        return "Not Yet Supported";
    },
    W: function(){
        return "Not Yet Supported";
    },
    F: function(){
        return Date.replaceChars.longMonths[this.getMonth()];
    },
    m: function(){
        return (this.getMonth() < 9 ? '0' : '') + (this.getMonth() + 1);
    },
    M: function(){
        return Date.replaceChars.shortMonths[this.getMonth()];
    },
    n: function(){
        return this.getMonth() + 1;
    },
    t: function(){
        return "Not Yet Supported";
    },
    L: function(){
        return (((this.getFullYear() % 4 == 0) && (this.getFullYear() % 100 != 0)) || (this.getFullYear() % 400 == 0)) ? '1' : '0';
    },
    o: function(){
        return "Not Supported";
    },
    Y: function(){
        return this.getFullYear();
    },
    y: function(){
        return ('' + this.getFullYear()).substr(2);
    },
    a: function(){
        return this.getHours() < 12 ? 'am' : 'pm';
    },
    A: function(){
        return this.getHours() < 12 ? 'AM' : 'PM';
    },
    B: function(){
        return "Not Yet Supported";
    },
    g: function(){
        return this.getHours() % 12 || 12;
    },
    G: function(){
        return this.getHours();
    },
    h: function(){
        return ((this.getHours() % 12 || 12) < 10 ? '0' : '') + (this.getHours() % 12 || 12);
    },
    H: function(){
        return (this.getHours() < 10 ? '0' : '') + this.getHours();
    },
    i: function(){
        return (this.getMinutes() < 10 ? '0' : '') + this.getMinutes();
    },
    s: function(){
        return (this.getSeconds() < 10 ? '0' : '') + this.getSeconds();
    },
    e: function(){
        return "Not Yet Supported";
    },
    I: function(){
        return "Not Supported";
    },
    O: function(){
        return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + '00';
    },
    P: function(){
        return (-this.getTimezoneOffset() < 0 ? '-' : '+') + (Math.abs(this.getTimezoneOffset() / 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() / 60)) + ':' + (Math.abs(this.getTimezoneOffset() % 60) < 10 ? '0' : '') + (Math.abs(this.getTimezoneOffset() % 60));
    },
    T: function(){
        var m = this.getMonth();
        this.setMonth(0);
        var result = this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/, '$1');
        this.setMonth(m);
        return result;
    },
    Z: function(){
        return -this.getTimezoneOffset() * 60;
    },
    c: function(){
        return this.format("Y-m-d") + "T" + this.format("H:i:sP");
    },
    r: function(){
        return this.toString();
    },
    U: function(){
        return this.getTime() / 1000;
    }
};
(function($){
    $.fn.center = function(absolute){
        return this.each(function(){
            var t = jQuery(this);
            t.css({
                position: absolute ? 'absolute' : 'fixed',
                left: '50%',
                top: '50%',
                zIndex: '99'
            }).css({
                marginLeft: '-' + (t.outerWidth() / 2) + 'px',
                marginTop: '-' + (t.outerHeight() / 2) + 'px'
            });
            if (absolute) {
                t.css({
                    marginTop: parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
                    marginLeft: parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
                });
            }
        });
    };
    $.fn.getFormValues = function(){
        var formvals = {};
        jQuery.each(jQuery(':input', this).serializeArray(), function(i, obj){
            if (formvals[obj.name] == undefined) 
                formvals[obj.name] = obj.value;
            else 
                if (typeof formvals[obj.name] == Array) 
                    formvals[obj.name].push(obj.value);
                else 
                    formvals[obj.name] = [formvals[obj.name], obj.value];
        });
        return formvals;
    }
    
    $.hideRoot = function () {
    		$("#nowPlaying").animate({height:"0"},{duration: 1000,specialEasing: {width: "linear"}}).removeClass('open').fadeOut('fast');
    		$.UI.player.animate({'padding-bottom':'0'},1000);
    }

    $.fn.navigate = function(){
		var url = 'navigator.php?q='+document.location.hash.substr(2);
		var key = document.location.hash;
		var stored = $.parseJSON($.storage.get({key: key}));
        if ($('html').hasClass('localstorage') && stored && typeof(stored) == 'object') {
            	   var mins = 900;
            		var now = Math.floor(new Date().getTime() / 1000);
            		var then = Math.floor(stored.time/1000);
            		var gap = now-then;
            		if(mins > gap) {
            			$.UI.player.fadeTo(50);
            			var data = unescape(stored.data);
            			$.UI.player.html(data).fadeIn(250);
            			
            			delete stored;
            		} else {
            			localStorage.removeItem(key);
            			$.getPage(url);
            		}
        } else {
			$.getPage(url);
		}
		igrooves.setUpUi();
    }
    $.getPage = function (url) {
    	      $.ajax({
                url: url,
                data : {
            			back: $.backHash,
            			js: true
            		},
                success: function(data){
                    if (data.length > 0) {
                    	$.UI.player.fadeTo(50).html(unescape(data)).fadeIn(250);
                       // $.UI.player.empty().html(data);
                        delete data;
                    }
                }
            });
        _gaq.push(['_trackEvent', 'Navigation', 'clicked', url]);
        $.backHash = url;
    }
    $.fn.cleanup = function(){
        if ($(this).children('.tempPage').length > 5) {
            $(this + '> .tempPage:first').remove();
        }
    }
    $.console = function(message){
        if (typeof(console) != 'undefined') {
            console.log(message);
        }
    }
    $.delays = {};
    $.delay = function (options) {
        if(typeof(options.name) != 'string' || typeof(options.callback) != 'function') {return false;}
        var defaults = {
            period : 200,
        }
        var setup =  $.extend(defaults,options);
        $.delay[setup.name] = setTimeout(setup.callback.call(this), setup.period); 
    }
    $.delayStop = function (name) {
            try{
                clearTimeout(name);
                return true;
            } catch (e){
                $.console(e);
            }
    }
    $.quickSearch = {
        send: function(){
            var query = $('#search_string').val();
            if (query.length > 0) {
            		$.rest.get.quickSearch(query);
            }
        },
        recieve : function (response) {
            var stored = $.parseJSON(sessionStorage.getItem('searchQueries'));
            var results = response.data;
            var html = $('#quickSearch');
            html.empty();
            if(results.bands) {
               html.append('<div class="title"><h3>Artists</h3><a>More...</a></div>');
               for (i=0;i<=results.bands.length-1;i++) {
                   html.append('<a class="entry"><img src="http://song.static.igm.me/mediaimage/band_image/'+results.bands[i].bid+'/35/35/image.png" align="left" />'+
                    '<h4>'+results.bands[i].name+'</h4>'+
                    '<span>'+results.bands[i].location+'</span>'+
                   '</a>');
               }
            }
            if(results.songs) {
               html.append('<div class="title"><h3>Tracks</h3><a>More...</a></div>');
               for (i=0;i<=results.songs.length-1;i++) {
                   html.append('<a class="entry"><img src="http://song.static.igm.me/mediaimage/song_image/'+results.songs[i].bid+'/'+results.songs[i].mid+'/35/35/image.png" align="left" />'+
                    '<h4>'+results.songs[i].name+'</h4>'+
                    '<span>'+results.songs[i].band+'</span>'+
                   '</a>');
               }
            }
            if(results.albums) {
               html.append('<div class="title"><h3>Albums</h3><a>More...</a></div>');
               for (i=0;i<=results.albums.length-1;i++) {
                   html.append('<a class="entry"><img src="http://song.static.igm.me/mediaimage/song_image/'+results.albums[i].bid+'/'+results.albums[i].mid+'/35/35/image.png" align="left" />'+
                    '<h4>'+results.albums[i].name+' ('+results.albums[i].songs+' tracks)</h4>'+
                    '<span>'+results.albums[i].band+'</span>'+
                   '</a>');
               }
            }
            if(results.videos) {
               html.append('<div class="title"><h3>Videos</h3><a>More...</a></div>');
               for (i=0;i<=results.videos.length-1;i++) {
                   html.append('<a class="entry"><img src="http://song.static.igm.me/mediaimage/video_image/'+results.videos[i].bid+'/'+results.videos[i].mid+'/35/35/image.png" align="left" />'+
                    '<h4>'+results.videos[i].name+'</h4>'+
                    '<span>'+results.videos[i].band+'</span>'+
                   '</a>');
               }
            }
        }
    }
    $(window).ready(function () {
        $.windowHeight = $(this).height();
        $.windowWidth = $(this).width()-120;
    }).resize(function () {
        $.windowHeight = $(this).height();
        $.windowWidth = $(this).width()-120; 
    });
    $.epoch2Date = function (time){
    		var date = new Date(1000*time);
    		return date.toUTCString();
    }
    $.fn.seek = function () {
		this.mousedown(function (e) {
			$.dragging = true;
			var pc = player.media.length*(e.pageX/$.windowWidth);
			player.sm.setPosition(player.playid, pc);
			$('body').bind('mousemove', function (e) {
				var pc = player.media.length*(e.pageX/$.windowWidth);
				player.sm.setPosition(player.playid, pc);
			});
		});
		$('body').mouseup(function (e) {
			$(this).unbind('mousemove');
			$.dragging = false;
		});
	};
		document.onselectstart = function() {
			if($.dragging) { 
				return false; 
			}
	}
	$.rest = {
		get : {
			server : 'http://rest.igrooves.net',
			fetch : function (data, handler, url) {
				if(!url) var url = $.rest.get.server;
				if($.userInfo && $.userInfo.data != null) data.ubid = $.userInfo.data.user_band_id, data.uid = $.userInfo.data.user_id;
				$.ajax({
					url : url,
					data : data,
					dataType : 'jsonp',
					success : function (response) {
						handler.call(this, response);
					},
					error : function (e) {
						console.log(e);
					}
				})
			},
			playlists : function () {
				
			},
			editPlaylist : function () {
				
			},
			userInfo :  function () {
				data = {
					method : 'userInfo'
				};
				url = "http://igrooves.net/rest_p.php"
				handler = function (response) {
					$.userInfo = response;
					if(response.ape && $.channels.length === 0) {
						$.channels = [];
						var i;
						for (i=0;i<=response.ape.length-1;i++) {
							$.channels.push(response.ape[i].ape);
						}
					}
				}
				$.rest.get.fetch(data,handler,url);
			},
			userTotals : function () {
				
			},
			feed : function () {
				
			},
			followers : function () {
				
			},
			following : function () {
				
			},
			updates : function  () {
				
			},
			comments : function (type, id){
				data = {
					method : 'comments',
					id: id,
					type : type
				}
				hander = function (response) {
					console.log(response);
				}
				$.rest.get.fetch(data,handler);
			},
			quickSearch : function (q) {
				data = {
					method : 'quickSearch',
					q : q
				};
				handler = function (response) {
					$.quickSearch.recieve(response);
				}
				$.rest.get.fetch(data,handler);
			},
			songInfo : function (id) {
				data = {
					method : 'songInfo',
					song_id : id
				};
				handler = function (response) {
					if(!response.data) return false;
					if(!$('#igrooves_base').hasClass('open')){
		                clearTimeout($.animation_timeout);
		                $.UI.player.css('padding-bottom','130px');
		                $('#nowPlaying').empty();
		                $('#tpl-nowPlaying').tmpl(response.data).appendTo('#nowPlaying');
					    	$('#nowPlaying').show().animate(
					    			{
					    				height:"170px"
					    				},  
					    			{
					    			duration: 300,
					    			specialEasing: {
					      			width: 'linear'
					      		}
					    		}).addClass('open');
					    	$.animation_timeout = setTimeout("$.hideRoot()	",4000);
				    	}
				    	FB.XFBML.parse();
	            		gapi.plusone.render();
				}
				$.rest.get.fetch(data,handler)
			} 
		},
		put : {
			server : 'http://igrooves.net/rest_p.php',
			write : function (data,handler) {
				$.ajax({
					url : $.rest.put.server,
					data : data,
					dataType : 'jsonp',
					success : function (response) {
						handler.call(this, response);
					},
					error : function (e) {
						console.log(e);
					}
				})
			},
			addFan : function (param) {
				var data = {
					method : "addFan"
				}
				data = $.extend(data,param);
				handler = function (response) {
					console.log(response);
				}
				$.rest.put.write(data,handler);
			}
		}
	}
	$.userInfo = $.rest.get.userInfo();
	$.onlogin = false;
	$.channels = [];
	$.timeStamp = function () {
		var d = new Date();
		return d.getTime();
	}


	$.trimWhiteSpace = function(str) {
		str = str.replace(/^\s+/, '');
		for(var i = str.length - 1; i >= 0; i--) {
			if(/\S/.test(str.charAt(i))) {
				str = str.substring(0, i + 1);
				break;
			}
		}
		return str;
	}

})(jQuery);

