/**
 * iTunes Lookup URL
 *
 * @var string itunesLookup
 */
//var itunesLookup = 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=290924565&entity=album';
var itunesLookup = 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup';
Date.prototype.toMMDDYYYYString = function () {return isNaN (this) ? 'NaN' : [this.getMonth() > 8 ? this.getMonth() + 1 : '0' + (this.getMonth() + 1), this.getDate() > 9 ? this.getDate() : '0' + this.getDate(), this.getFullYear()].join('/')}
/**
 * iTunes Search URL
 *
 * @var string itunesSearch
 */
//var itunesSearch = 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?term=16bit&limit=25';
var itunesSearch = 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch?';
/**
 * iTunes Affiliate Link URL
 *
 * @var string itunesAffiliateLink
 */
var itunesAffiliateLink = 'http://click.linksynergy.com/fs-bin/stat?id=7SzOrKOKALE&offerid=146261&type=3&subid=0&tmpid=1826&RD_PARM1=';

/**
 * Row String Length - This is the maximum number of characters strings should take
 *
 * @var integer rowStringLength
 */
var rowStringLength = 24;

/**
 * The array of iTunes Months
 *
 * @var array iTunesMonth
 */
var iTunesMonth=new Array(12);

iTunesMonth[0]="January";
iTunesMonth[1]="February";
iTunesMonth[2]="March";
iTunesMonth[3]="April";
iTunesMonth[4]="May";
iTunesMonth[5]="June";
iTunesMonth[6]="July";
iTunesMonth[7]="August";
iTunesMonth[8]="September";
iTunesMonth[9]="October";
iTunesMonth[10]="November";
iTunesMonth[11]="December";

////////////////////////////////////////////////////////////////////////////////
//
// helpers
//
////////////////////////////////////////////////////////////////////////////////

/**
 * isset
 *
 */
function isset(varname){
    if (typeof(varname) == "undefined")
    {
        return false;
    }
    else {
        return true;
    }
}

/**
 * Pad out a number with a single zero for a two digit format: 01
 *
 */
function padout(number)
{
    return (number < 10) ? '0' + number : number;
}

/**
 * Make an Itunes Affiliate Link
 *
 */
function makeItunesAffiliateLink(iTunesLink)
{
    return itunesAffiliateLink + escape(escape(iTunesLink + '&partnerId=30'));
}

////////////////////////////////////////////////////////////////////////////////
//
// iTunes
//
////////////////////////////////////////////////////////////////////////////////

/**
 * Format a date: 1987-01-01T08:00:00Z
 *
 * This is used for releaseDate
 *
 * @link http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=305328946&entity=song
 *
 * @return string January 1, 1987
 */
function itunesDate(myDateString)
{
    var myReturn = '';
    
    //alert('myDateString: ' + myDateString);
    if (isset(myDateString)) {
        //alert('true - myDateString: ' + myDateString);

        var myDateTime = myDateString.split('T');
        var myDate = myDateTime[0];
        var myTime = myDateTime[1];
    
        var myDateYMD = myDate.split('-');
        //alert('myDateYMD.length: ' + myDateYMD.length);
        if (myDateYMD.length = 3) {
            
            var myDateY = myDateYMD[0];

            //alert('parseInt(' + myDateYMD[1] + ', 10): ' + parseInt(myDateYMD[1], 10));
            var myDateM = iTunesMonth[ (parseInt(myDateYMD[1], 10) - 1) ];

            var myDateD = myDateYMD[2];
            
            myReturn = myDateM + ' ' + myDateD + ', ' + myDateY;
        }
    }
    else {
        //alert('false - myDateString: ' + myDateString);
    }
    
    return myReturn;
}

//http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=305328958
function timeMilliToMinutes(millitime)
{
    var myTime = Math.ceil(millitime / 1000);
    var formatedTime = '';
    var testTime = '';
    
    //testTime += myTime + ' seconds ->'
    myRemainder = myTime % 60;
    testTime += Math.floor(myTime / 60) + ':'
    testTime += padout(myRemainder);

    return testTime;

    myRemainder = myTime % 60;
    formatedTime += Math.floor(myTime / 60) + ':';

    formatedTime += Math.floor(myRemainder / 60);
    
    return formatedTime;
}

function getItunesTracks_Album(data, options)
{
    var html = '';

    html += '<ul>';
    html += '    <li>';
    html += '        <div style="float: left; margin-right: 2em;">';
    html += '            <img src="' + data.artworkUrl100 + '" width="100px" height="100px" alt="Album Art" />';
    html += '        </div>';
    html += '        <div style="float: left;">';
    html += '            <ul>';
    
    if (isset(options)) {
        if (isset(options.display) && options.display == 'label') {
            html += '                <li>' + data.artistName + '</li>';
            //html += '                <li>' + data.collectionName + '</li>';
        }
    }
    
    if (isset(options)) {
        if (isset(options.studioLabel)) {
            if (isset(options.studioLabelId)) {
                html += '                <li><a href="/label-profile.php?id=' + options.studioLabelId + '">' + options.studioLabel + '</a></li>';
            }
            else {
                html += '                <li>' + options.studioLabel + '</li>';
            }
        }
    }
    
    html += '                <li>' + itunesDate(data.releaseDate) + '</li>';
    
    //html += '                <li>' + data.copyright + '</li>';
    html += '                <li>';
    html += '                    <div style="float: left; margin-right: 2em; font-size: larger;">$' + data.collectionPrice.toFixed(2) + '</div>';
    html += '                    <a target="_blank" href="' + makeItunesAffiliateLink(data.collectionViewUrl) +'">';
    html += '                        <img style="width: ; height: ;" src="/images/download-itunes.png" alt="Download from iTunes" />';
    html += '                    </a>';
    html += '                </li>';
    html += '            </ul>';
    html += '        </div>';
    html += '        <div class="clear">';
    html += '    </li>';
    html += '</ul>';

    return html;
}

function getItunesTracks_Tracks(data, options)
{
    var html = '';
    var price = (data.trackPrice >= 0) ? '$' + data.trackPrice.toFixed(2) : 'Album Only'

    html += '        <tr>';
    html += '            <td>';
    //html += playSongHtml(data.previewUrl);
    html += '                <a class="media" href="' + data.previewUrl + '"></a>';
    //html += '                <a href="' + data.previewUrl + '" title="Preview ' + data.trackCensoredName + '">';
    //html += '                    <img style="width: 24px; height: 24px;" src="/images/player_play.png" alt="Play" />';
    //html += '                </a>';
    html += '            </td>';
    html += '            <td>' + data.trackNumber + '</td>';
    html += '            <td>' + data.trackCensoredName + '</td>';
    html += '            <td>' + timeMilliToMinutes(data.trackTimeMillis) + '</td>';
    html += '            <td>' + price + '</td>';
    html += '        </tr>';



    return html;
}

function getItunesTracks(collectionId, styleId, options)
{
    //alert('collectionId :' + collectionId);
    //alert('options :' + options);
    if (!isset(options)) {
        //alert('options: ' + options);
    }
    //return false;
    $(document).ready(function()
        {
            var myUrl = itunesLookup;
            //myUrl += '?id=' + collectionId + '&entity=song';
            //alert('myUrl: ' + myUrl);
            //alert('limit: ' + limit);
            //if (limit == undefined) {
            //    limit = 3;
            //}
            //var artistName = '16bit';
            
            $.ajax(
                {
                    url: myUrl,
                    //url: 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=290924565&entity=album',
                    dataType: 'jsonp',
                    data: {'id':collectionId, 'entity':'song'}, 
                    //data: "name=John&location=Boston",
                    success: function(j)
                    {
                        //alert('success');
                        //alert('j.results.length: ' + j.results.length);
                        
                        if (j.results.length > 0) {
                            var album = '';
                            var tracks = '';
                            var html = '';
                            // Open list tag
            
            
                            for (var i = 0; i < j.results.length; i++) {
                                if (j.results[i].wrapperType == 'track') {
                                    tracks += getItunesTracks_Tracks(j.results[i], options);
                                }
                                else if (j.results[i].wrapperType == 'collection') {
                                    album += getItunesTracks_Album(j.results[i], options);
                                }


                            }
        
                            html += album;

                            html += '    <table>';
                            html += '        <tr>';
                            html += '            <th style="width: 32px;"></th>';
                            html += '            <th style="width: 32px;">#</th>';
                            html += '            <th>Song Name</th>';
                            html += '            <th style="width: 60px;">Time</th>';
                            html += '            <th style="width: 60px;">Price</th>';
                            html += '        </tr>';

                            html += tracks;

                            html += '    </table>';

                            // Close list tag
                            //$("#albums").html(options);
                            $('#' + styleId).html(html);
                            $('a.media').media( { width: 17, height: 20 } );
                        }
                    }
                }
            );
        }
    );
 
}

function getItunesAlbums(artistId, styleId, limit)
{
    var myUrl = itunesLookup;
    //myUrl += 'id=' + artistId + '&entity=album';
    //alert('myUrl: ' + myUrl);
    //alert('limit: ' + limit);
    if (limit == undefined) {
        limit = 3;
    }
    //var artistName = '16bit';
    
    $.ajax(
        {
            url: myUrl,
            //url: 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=290924565&entity=album',
            dataType: 'jsonp',
            data: {'id':artistId, 'entity':'album', 'limit':limit}, 
            //data: "name=John&location=Boston",
            success: function(j)
            {
                //alert('success');
                //alert('j.results.length: ' + j.results.length);
                
                if (j.results.length > 0) {
                    var html = '';
                    /*
                    var items = new Array();
                    
                    for (var i = 0; i < j.results.length; i++) {
                        if (j.results[i].wrapperType == 'collection') {
                            items.push(j.results[i].releaseDate);
                            items[ j.results[i].releaseDate ] = j.results[i];
                        }
                    }
                    
                    items.sort();
                    items.reverse();

                    html += '<ul>';
                    for (var i = 0; i < items.length; i++) {
                        html += '<li>';
                        html += items[i] + ' - ' + items[i].collectionName;
                        html += '</li>';
                    }
                    html += '</ul>';
                    //*/
                    // Open list tag
                    html += '<ul>';
    
    
                    for (var i = 0; i < j.results.length; i++) {
                        if (j.results[i].wrapperType == 'collection') {
                            html += '    <li>';
                            html += '        <div class="image">';
                            html += '            <img src="' + j.results[i].artworkUrl60 + '" width="60px" height="60px" alt="Album Art" />';
                            html += '        </div>';
                            html += '        <div class="info">';
                            html += '            <ul>';
                            html += '                <li>' + j.results[i].collectionName + '</li>';
                            
                            myDate = new Date(j.results[i].releaseDate);
                            
                            html += '                <li>' + myDate.toString() + '</li>';
                            html += '                <li>' + j.results[i].copyright + '</li>';
                            html += '            </ul>';
                            html += '        </div>';
                            html += '        <div class="clear">';
                            html += '    </li>';
                        }
                    }

                    // Close list tag
                    html += '</ul>';
                    //$("#albums").html(options);
                    $('#' + styleId).html(html);
                }
            }
        }
    );
/*
    $.ajax(
        {
            url: "http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsSearch",
            dataType: 'jsonp',
            data: {'term':artistName, 'limit':'25'}, 
            success: function(j)
            {              
                var options = '';
                for (var i = 0; i < j.results.length; i++) {
                    //options += '<option value="' + j.results[i].trackId + '">' + j.results[i].artistName + ' - ' + j.results[i].trackCensoredName + '</option>';
                    options += '<p>' + j.results[i].trackId + ' - ' + j.results[i].artistName + ' - ' + j.results[i].trackCensoredName + '</p>';
                }
                $("#albums").html(options);
            }
        }
    );
    $.getJSON(
        myUrl,
        function(data)
        {
            alert('data: ' + data);
            $.each(data.results, 
                function(i,results)
                {
                    alert('results.wrapperType: ' + results.wrapperType);
                    //$("<img/>").attr("src", item.media.m).appendTo("#images");
                    if ( i == 3 ) return false;
                }
            );
        }
    );
*/    
 
}


function getItunesPodcasts(artistId, styleId)
{
    //alert('collectionId :' + collectionId);
    //return false;

    $(document).ready(function()
        {
            var myUrl = itunesLookup;
            //myUrl += 'id=' + artistId + '&entity=podcast';
            //alert('myUrl: ' + myUrl);
            //alert('limit: ' + limit);
            //if (limit == undefined) {
            //    limit = 3;
            //}
            //var artistName = '16bit';
            
            $.ajax(
                {
                    url: myUrl,
                    //url: 'http://ax.phobos.apple.com.edgesuite.net/WebObjects/MZStoreServices.woa/wa/wsLookup?id=20318188&entity=podcast',
                    dataType: 'jsonp',
                    data: {'id':artistId, 'entity':'podcast'}, 
                    //data: 'id=' + '&entity=podcast',
                    success: function(j)
                    {
                        //alert('success');
                        //alert('this.url: ' + this.url);
                        //alert('j.results.length: ' + j.results.length);
                        
                        if (j.results.length > 1) {
                            var album = '';
                            var tracks = '';
                            var trackName = '';
                            var html = '';
                            // Open list tag
            
                //html += '            <img src="' + data.artworkUrl100 + '" width="100px" height="100px" alt="Album Art" />';

                            for (var i = 0; i < j.results.length; i++) {
                                //alert('j.results[i].wrapperType: ' + j.results[i].wrapperType);
                                if (j.results[i].wrapperType == 'track') {
                                    tracks += '<div class="itunes-float">';
                                    tracks += '<div class="image">';
                                    tracks += '<img src="' + j.results[i].artworkUrl60 + '" alt="Album Art: ' + j.results[i].trackCensoredName + '" />';
                                    tracks += '</div>';
                                    tracks += '<div class="info">';
                                    tracks += '<ul>';
                                    
                                    trackName = j.results[i].trackCensoredName;
                                    
                                    if (trackName.length > rowStringLength) {
                                        trackName = trackName.substr(0, rowStringLength);
                                    }
                                    
                                    tracks += '<li><span title="' + j.results[i].trackCensoredName + '">' + trackName + '</span></li>';
                                    tracks += '<li>';
                                    //tracks += j.results[i].previewUrl;
                                    //tracks += '<a class="podcast" href="' + j.results[i].previewUrl + '">';
                                    tracks += '<a target="_blank" class="podcast" href="' + makeItunesAffiliateLink(j.results[i].trackViewUrl) + '" title="Listen on iTunes - ' + j.results[i].trackCensoredName + '">';
                                    tracks += '<img style="padding-top: .5em; width: 82px; height: 30px;" src="/images/itunes-subscribe.gif" alt="Subscribe from iTunes" />';
                                    tracks += '</a>';
                                    tracks += '</li>';
                                    tracks += '</ul>';
                                    tracks += '</div>';
                                    tracks += '<div class="clear"></div>';
                                    tracks += '</div>';
                                }
                                else if (j.results[i].wrapperType == 'artist') {
                                    //album += getItunesTracks_Album(j.results[i]);
                                }


                            }
        
                            //html += album;
                            html += '<h2>iTunes Podcasts</h2>';
                            html += '<div class="clear"></div>';



                            //html += '    <table>';
                            //html += '        <tr>';
                            //html += '            <th style="width: 32px;"></th>';
                            //html += '            <th style="width: 32px;">#</th>';
                            //html += '            <th>Song Name</th>';
                            //html += '            <th style="width: 60px;">Time</th>';
                            //html += '            <th style="width: 60px;">Price</th>';
                            //html += '        </tr>';

                            html += tracks;

                            //html += '    </table>';

                            // Close list tag
                            //$("#albums").html(options);
                            $('#' + styleId).html(html);
                            //$('a.podcast').media( { width: 60, height: 20 } );
                        }
                    }
                }
            );
        }
    );
 
}


function playSongHtml(file)
{
    var html = '';
    return html;

    html += "\n" + '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="17" height="17" codebase="//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">';
    html += '\n<param name="movie" value="/mp3Player.swf" /><param name="wmode" value="transparent" />';
    html += '\n<param name="flashvars" value="filename=' + file + '" />';
    html += '<embed wmode="transparent" src="/mp3Player.swf" flashvars="filename=' + file + '" type="application/x-shockwave-flash" width="17" height="17" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    html += '</object>';
    
        
        
        
    
    return html;

    html += '<!-- Generated by AudioPlay Online Generator (http://www.strangecube.com/audioplay/) -->';
    html += '<div>';
    html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="15" height="15">';
    html += '<PARAM NAME=movie VALUE="http://www.strangecube.com/audioplay/online/audioplay.swf?file=' + file + '&auto=no&sendstop=yes&repeat=0&buttondir=http://www.strangecube.com/audioplay/online/alpha_buttons/negative_small&bgcolor=0xffffff&mode=playpause"/>';
    html += '<PARAM NAME=quality VALUE=high/>';
    html += '<PARAM NAME=wmode VALUE=transparent/>';
    html += '<embed src="http://www.strangecube.com/audioplay/online/audioplay.swf?file=' + file + '&auto=no&sendstop=yes&repeat=0&buttondir=http://www.strangecube.com/audioplay/online/alpha_buttons/negative_small&bgcolor=0xffffff&mode=playpause" quality=high wmode=transparent width="15" height="15" align="" TYPE="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">';
    html += '</embed>';
    html += '</object>';
    html += '</div>';
    html += '<!-- End of generated code -->';

    return html;

}


////////////////////////////////////////////////////////////////////////////////
//
// The Untz Functions
//
////////////////////////////////////////////////////////////////////////////////

/* 
bindWithDelay jQuery plugin
Author: Brian Grinstead
http://github.com/bgrins/bindWithDelay
Open source code under MIT license: http://www.opensource.org/licenses/mit-license.php

Usage: 
	See http://api.jquery.com/bind/
	.bindWithDelay( eventType, [ eventData ], handler(eventObject), timeout )

Examples:
	$("#foo").bindWithDelay("click", function(e) { }, 100);
	$(window).bindWithDelay("resize", { optional: "eventData" }, callback, 1000);
*/

(function($) {
$.fn.bindWithDelay = function( type, data, fn, timeout ) {
	var wait = null;
	var that = this;
	
	if ( $.isFunction( data ) ) {
		timeout = fn;
		fn = data;
		data = undefined;
	}
		
	var cb = function(e) {
		clearTimeout(wait);
		var cachedEvent = $.extend({}, e);
		
		wait = setTimeout(function() {
			fn.apply(that, [cachedEvent]);
		}, timeout);
	}
	
	return this.bind(type, data, cb);
}
})(jQuery);

