window.onerror  = function (){return false};

var playerDoc;
var inc = 0;

var storeURL = "https://store.slacker.com/store/";
var siteURL = "http://www.slacker.com";
var forumsURL = "http://forums.slacker.com";
var env = "PROD";
if(top.location.toString().indexOf(".stg") > -1){
    storeURL = "https://store.stg.sdslacker.com/store/";
    siteURL = "http://www.stg.sdslacker.com";
    forumsURL = "http://forums.stg.sdslacker.com";
    env = "STG";
}
else if(top.location.toString().indexOf(".stg2") > -1){
    storeURL = "https://store.stg2.sdslacker.com/store/";
    siteURL = "http://www.stg2.sdslacker.com";
    forumsURL = "http://forums.stg2.sdslacker.com";
    env = "STG2";
}
else if(top.location.toString().indexOf(".dev") > -1){
    storeURL = "https://store.dev.sdslacker.com/store/";
    siteURL = "http://www.dev.sdslacker.com";
    forumsURL = "http://forums.dev.sdslacker.com";
    env = "DEV";
}
else if(top.location.toString().indexOf("xeno") > -1){
    storeURL = "http://xeno.dev.sdslacker.com/store/";
    siteURL = "http://xeno.dev.sdslacker.com";
    forumsURL = "http://forums.xeno.dev.sdslacker.com";
    env = "XENO";
}



/*Create a class that holds specific bits for the site pages.*/
function siteSpace(){
    this.newSiteWin;
    this.iframe;
    this.modalWin;
    this.FBtext = "  What do you think?  Type your feedback here and then hit Submit.";
    this.copyright   = 'Copyright &copy; 2008 Slacker, Inc.';
    this.createST = (!opener)?"<a href=\"javascript:player.com.rockit.webplayer.pageUtils.goToEditStationPage();\">\"Create Station\"</a>":"\"Create Station\"";
    this.QUOTES   = new Array(
    ["The Slacker Portable faithfully recreates the look and feel of the web-based application, and looks to be the most intriguing player of 2008.", "LAPTOP Magazine"],
    ["It's an intuitively adaptive Internet radio service that learns what music you love...It is just now lighting up and trust me, it's way cool.","Sound & Vision Magazine"],
    ["The Slacker Portable is a groundbreaking, innovative device that I'd recommend to music fans of all varieties.","WIRED"],
    ["Slacker leaves its radio peers in the dust.","Filter Magazine "],
    ["Slacker is no slouch... within about 30 seconds of first arriving... you can be listening to your pick of a huge number of potential stations.","PC World"],
    ["Slacker has been busy perfecting Internet radio for a pocket-sized player","Paste Magazine"],
    ["The Slacker Portable faithfully recreates the look and feel of the web-based application, and looks to be the most intriguing player of 2008.","LAPTOP Magazine"],
    ["The cool thing is that once you buy the player, the service is free... It's like having a magic iPod that always has new music for you to listen to.","The Gadgeteer"]
    );

    this.NextPrevious = new Array();
    this.playerLoaded   = false;
    this.homeBanner;
    this.bannerTimer;
    this.ads;
};
// Class methods
siteSpace.prototype  = {
    showQuotes    : function() {
        var maxLen      = this.QUOTES.length;
        var whichQuotes   = Math.floor(Math.random()*maxLen);
        var openD = "<div id=\"quote\">\"";
      var closeD= "\"</div><br/><div id=\"quotee\">&mdash; ";
        jQuery("#home_testimonial").html(openD + this.QUOTES[whichQuotes][0] + closeD + this.QUOTES[whichQuotes][1] + "</div>");
    },
    getCopyright    : function (bWrite) {
        if (bWrite) {
            document.write(this.copyright);
        } else {
            return this.copyright;
        }
    },
    isFirstTime  : function () {
        var timeLeft    = 24 - (((new Date()).getTime() - window.frames['player'].globalCookie.fl)/1000/3600);
        return parseFloat(timeLeft) > 24; /*First time visitors will have this value be approx 24.3*/
        //return true;
    },
    getFirstLaunch  : function () {
       return  parseInt(24 - (((new Date()).getTime() - window.frames['player'].globalCookie.fl)/1000/3600));
    },
    checkPlayerLoaded    : function () {
        //if(jQuery('#'+"playerArea")){
            var win    = window.frames['player'];
            var tmp = win.RockitDevice;
            if (tmp) {
                require("com.gui.widget.ads");
                this.ads = com.gui.widget.ads;
                /*Hook up home page banner to web player events, and get first banner*/
                /*
                tmp.player.attachEvent("OnPlay", function (evt, t) {
                    if (t && t.metadata.get("type") == "radio") {
                        SITE.rotateHomeBanner("wp",{aamsz:"187x388",area:"home"});
                    }
                });
                */
                var targets  = {aamsz:"300x600",area:"home",fv:(SITE.isFirstTime())?1:0,lage:SITE.getFirstLaunch()};
                // Capture any click on the web player as an ad rotation trigger
                try {
                    win.document.getElementById("canvas").attachEvent("onmousedown", function (evt) {
                        SITE.rotateHomeBanner("wp",targets);
                    });
                } catch (e){
                    win.document.getElementById("canvas").addEventListener("mousedown", function (evt) {
                        SITE.rotateHomeBanner("wp",targets);
                    },true);
                }
                // Other events
                tmp.attachEvent("OnLoadingComplete", function (evt) {
                    // Load initial banner
                    SITE.playerLoaded  = true;
                    SITE.rotateHomeBanner("wp",targets);
                });
                tmp.attachEvent("OnServiceLogin", function (evt) {
                    if (SITE.playerLoaded) {
                        SITE.rotateHomeBanner("wp",targets,true);
                    }
                });
                tmp.attachEvent("OnServiceLogout", function (evt) {
                    if (SITE.playerLoaded) {
                        SITE.rotateHomeBanner("wp",targets,true);
                    }
                });
            } else {
                setTimeout(function (){SITE.checkPlayerLoaded()},100);
            }
       //}
    },
    goHome   : function () {
        var arg = arguments[0];
        try {
            window.opener.frames
        } catch (e) {
            window.opener = null;
        }
        if (window.opener) {
            window.opener.focus();
            if (navigator.userAgent.indexOf("MSIE") > -1) {
                try {
                    window.opener.SITE.newSiteWin.close();
                } catch (e) {

                }
            }
            else {
                window.close();
            }
        }
        else {
            if( arg != "undefined" && arg == true){
                location.href  = siteURL + "/";
            }
            else{
                location.href  = "/";
            }
        }
    },
    goToPage    : function (pg) {
        var arg = arguments[1];
        var x_env = pg;
        if( arg != "undefined"){
            if(arg == 1){ x_env = storeURL + pg; }
            else if(arg == 2){x_env = forumsURL + pg; }
            else { x_env = siteURL + pg; }
        }
        if (this.newSiteWin  && !this.newSiteWin.closed && this.newSiteWin.location) {
            this.newSiteWin.location.href  = x_env;
        }
        else {
            this.newSiteWin = window.open(x_env);
            if (!this.newSiteWin.opener) this.newSiteWin.opener = self;
        }
        if (this.newSiteWin.focus) {this.newSiteWin.focus()}
        return false;
    },
    accountSignUp   : function () {
        try {
            window.opener.frames
        } catch (e) {
            window.opener = null;
        }
        if (window.opener) {
            window.opener.frames['player'].RockitDevice.login(null,"Sign up for your free Slacker account or log in if you already have one.");
            this.goHome();
        } else {
            try {
                window.frames['player'].RockitDevice.login(null,"Sign up for your free Slacker account or log in if you already have one.");
            } catch (e) {
                this.goHome();
            }
        }
    },
    rotateHomeBanner   : function (site, extraTargets, bForce) {
        if (!this.bannerTimer || bForce) {
            var sessLen = null;
            if (!this.ads) {
              require("com.gui.widget.ads");
              this.ads = com.gui.widget.ads;
            }
            var stateTargets = {};
            /*Create the banner instance.*/
            if (!this.homeBanner) {
                this.homeBanner  = new this.ads.bannerAd(document.getElementById('bannerContainer'),{
                    id  : "testAd",
                    img : document.getElementById('leftSkyscraper'), /*Allows default image to be in place for page load*/
                    server  : "/clicktrack/hserver"
                });
            }
            /*Set up our user state targeting.*/
            if (window.frames['player']) {
                var device    = window.frames['player'].RockitDevice;
                // Define global var for ad callbacks from clickthrough actions.
                RockitDevice    = device;
                sessLen = Math.ceil(((new Date()) - device.id)/1000/60); // Session length in minutes
                stateTargets = this.homeBanner.getUserTargets(device);
            }
            stateTargets['site']= site;
            stateTargets['fmt']= "xml";
            if (extraTargets) {
                for (i in extraTargets) {
                    stateTargets[i]  = extraTargets[i];
                }
            }
            // Set targeting for this fetch
            this.homeBanner.def.serverParams   = stateTargets;
            this.homeBanner.fetch();
            //alert (this.homeBanner.url);
            // Reset banner mutex timer
            var mutexTime   = (sessLen && sessLen <= 5) ? 300000 : 60000; // exlusive for the first 5 min, then 1min thereafter
            this.bannerTimer    = setTimeout(function () {SITE.bannerTimer=null}, mutexTime)
        }
    },
    swapImage : function (src, img) {
        if (!src && img.oSrc) {
            img.src = img.oSrc;
        } else {
            img.oSrc = img.src; /*Store original source in case we need it.*/
            if (src) img.src = src;
        }
        return false;
    },
    createStation : function(){
      try{
          player.com.rockit.webplayer.pageUtils.goToEditStationPage();
          }
       catch(e){}
     },
     nextPrevious : function() {
     /* This is a VERY basic next function to plow through image arrays = "NextPrevious[]".
      * The LAST image in the array should be the DEFAULT or FIRST image dispayed.
      * TODO and decriment feature to step to previous.
      */
        var maxLen      = this.NextPrevious.length;
        if(jQuery("#nextPrevious") != "undefined" && maxLen >0){
        if(inc >= maxLen){ inc = 0; }
          //alert(this.NextPrevious[inc]);
          jQuery("#nextPrevious").html("<img id=\"portable_image\" src=\"" + this.NextPrevious[inc] + "\" alt=\"Portable Player Random Image\" />");
      inc=inc+1;
        }
        else{ void(0); }
    },
    crossBeacon : function(url) {
        // Use this if you need to ping a URL that is not in www.slacker.com
        var beacon = document.createElement("img");
        beacon.src   = url;
        setTimeout(function(){beacon=null},5000); // kill this reference after 5 sec.
    },
    beaconFarts : function(b){
        jQuery.ajax({
            url: "/beacon/WWW/"+b,
            type: "get",
            dataType: "html",
            complete: function(res, status){
                //alert(["complete", res, status]);
            }
        });
    },
  submitFeedbackForm : function(obj){
      objN = jQuery('#'+obj);
      var newMail = false;
      var warn = "Please Type your feedback first, then hit Submit!";
      if(objN.val().length >0 && objN.val() == SITE.FBtext ){
          alert(warn);
          return;
      }
      else{
        window.frames['player'].feedbackSubmit(document.forms['feedback']);
          document.jQuery("#feedbackTA").val(SITE.FBtext);
      }
  },
  feedbackSubmit : function(obj) {
        require("com.data.httpRequest");
        fVal = jQuery('#'+obj);
      var newMail = false;
      var text = "Type your feedback here and then hit Submit";
      var warn = "Please Type your feedback first.<br/>Then hit Submit!";
      var uname   = ( jQuery("#player").contents().find("#loggedInUsername")) ? jQuery("#player").contents().find("#loggedInUsername").text(): "";
      this.modalWin = new $($.fn.nyroModal.settings.openSelector).nyroModal();
      if(fVal.val().length >8 && (fVal.val()).indexOf(text)>=0){
            this.modalWin.nyroModalManual({
                 bgColor: '#333333',
                 height: 250,
                 width: 450,
                 type: 'div',
                 content: '<div class=\"modalContent\"><br/><h2>'+warn+'</h2> <button class="nyroModalClose">OK</button></div>'
            });
               setTimeout("jQuery.nyroModalRemove();",8000);
          return;
      }
      else{
            this.modalWin.nyroModalManual({
                 modal: false,
                 bgColor: '#3333cc',
                 height: 400,
                 width: 450,
                 type: 'div',
                 content: '<form id="feedbs" name="feedbs"  onsubmit="return false" enctype="application/x-www-form-urlencoded">'+
                         '<div class="modalContent"><h1 class="center">Slacker Feedback</h1><table>'+
                         '<tr><td class="m_fieldText"></td><td><span class="required">*</span> Recommended fields for a reply from Slacker</td></tr>'+
                         '<tr><td class="m_fieldText"><span class="required op" id="req_0">*</span> Your Name:</td><td class="m_field"><input type="text" id="fullname" name="fullname" value=""></td></tr>'+
                         '<tr><td class="m_fieldText"><span class="required op" id="req_1">*</span> Your Email:</td><td class="m_field"><input type="text" id="email" name="email"  value="'+uname+'"/></td></tr>'+
                         '<tr><td class="m_fieldText"><span class="required op" id="req_2">*</span> Send To:</td><td class="m_field">'+
                         '<select name="recipient" id="fbRecipient" onchange=\"updateSubject(this.selectedIndex)\">'+
                         '  <option value="0" selected="selected" value="feedback">General Feedback</option>'+
                         '  <option value="1">Marketing</option>'+
                         '  <option value="2">Partners</option>'+
                         '  <option value="3">Sales</option>'+
                         '  <option value="4">Slacker Radio & DJs</option>'+
                         '  <option value="5">Slacker Radio Content Problem</option>'+
                         '  <option value="6">Support</option>'+
                         '  <option value="7">Webmaster</option>'+
                         '</select>'+
                         '</td></tr>'+
                         '<tr><td class="m_fieldText"><span class="required op" id="req_3">*</span> Subject:</td><td class="m_field">'+
                         '<select name="subject" id="fbSubject">'+setFBoptions()+'</select>'+
                         '</td></tr>'+
                         '<tr><td class="m_fieldText top"><span class="required" id="req_4">*</span> Comments:</td><td class="m_field"><textarea id="comments"></textarea></td></tr>'+
                         '<tr><td class="m_btn" colspan="2"><button id="submitFB" onclick="SITE.fSubmit();void(0);">Submit</button>'+
                         '<button onclick="top.setFieldValue(\'feedbackTA\',null);jQuery.nyroModalRemove();">Cancel</button></td></tr>'+
                         '</table></div>'+
                         '</form>'
            });
        makeSublist('fbRecipient','fbSubject', true, '');
        updateSubject(0);
        jQuery('#comments').val(fVal.val());
        jQuery("#feedbs").validate({});
      }
      },
      fSubmit : function(){
           /*Make sure there is actually something in the form to submit.*/
             /*Close the Previous Modasl Window*/
             //jQuery.nyroModalRemove();
             var device  = window.frames['player'].RockitDevice;
             var uname   = (device.ui.getElementById("loggedInUsername").innerHTML)
                           ? device.ui.getElementById("loggedInUsername").innerHTML
                           : "";

            var p   = [];
            var currentStation    = device.getStationMetadata(device.player.metadata.get("stationId"));
            for (var k in device.userFlags) {
                if(k!='wsToken'&&k!='username'&&k!='check'&&k!='uptime') {
                    p[p.length] = k + "=" + ((device.userFlags[k]) ? device.userFlags[k] : "");
                }
                if (k=='uptime') {
                    var time    = (new Date()) - device.userFlags[k];
                    p[p.length] = "Session Length="+Number(time/3600000).toFixed(2)+" hrs";
                }
            }

            if (currentStation) {
                p[p.length] = "Current Station=" + currentStation.id + " - " + currentStation.name ;
            }

            p[p.length] = "Current Track=" + window.frames['player'].RockitDevice.player.currentTrack+ "\r\n";
            p[p.length] = "Guess connection speed: " + com.data.httpRequest.getConnSpeed() + "\r\n";
            p[p.length] = "Browser: " + navigator.userAgent;

            var data    = "Username (if logged in): " + uname + "\r\n\r\n" + "\r\n\r\nDiagnostics:\r\n\r\n" + p.join("\r\n") + "\r\n\r\n" + com.debug.console.getLog().join("\r\n");
      var sepx ="\r\n\r\n==================================================================== \r\n\r\n";
      var url = '/includes/formMail.php';
      var name_z = jQuery("#fullname").val();
      var name_t = name_z.replace(/(<([^>]+)>)/ig,"");
      var email_z = jQuery("#email").val();
      var email_t = email_z.replace(/(<([^>]+)>)/ig,"");
      if(name_t == ""){name_t = "No Name";}
      if(email_t == ""){email_t = "nobody@nowhere.com";}
      var comment_z = jQuery("#comments").val();
      var comment_t = comment_z.replace(/(<([^>]+)>)/ig,"");
      var suj_t = jQuery("#fbSubject").val();
      var rec_t = jQuery("#fbRecipient").val();
        switch(rec_t){
            case 1:
                rec_t = "Marketing";
              break;
            case 2:
                rec_t = "Partners";
              break;
            case 3:
                rec_t = "Sales";
              break;
            case 4:
                rec_t = "Slacker Radio & DJs";
              break;
            case 5:
                rec_t = "Slacker Radio Content Problem";
              break;
            case 6:
                rec_t = "Support";
              break;
            case 7:
                rec_t = "Webmaster";
              break;
            default:
                rec_t = "General Feedback";
        }

      jQuery.post(url, {
                content:comment_z + sepx + data ,
                subject: suj_t,
                email: email_t,
                fullname: name_t,
                sendTo: rec_t
            },
            function(data,textStatus) {
                ///alert("WTF::" +textStatus + "  " + suj_t +" ::: "+ rec_t);
                this.modalWin = new jQuery(jQuery.fn.nyroModal.settings.openSelector).nyroModal();
                this.modalWin.nyroModalManual({
                     modal: false,
                     bgColor: '#333333',
                     height: 300,
                     width: 450,
                     type: 'div',
                     content: '<div class=\"modalContent\"><h1 class=\"center\">Thank you for your feedback.<br/></h1><table>'+
                                '<tr><td class=\"m_fieldText\">Your Name:</td><td class=\"m_field\">'+name_t+'</td></tr>'+
                                '<tr><td class=\"m_fieldText\">Your Email:</td><td class=\"m_field\">'+email_t+'</td></tr>'+
                                '<tr><td class=\"m_fieldText\">Send To:</td><td class=\"m_field\">'+rec_t+'</td></tr>'+
                                '<tr><td class=\"m_fieldText\">Subject:</td><td class=\"m_field\">'+suj_t+'</td></tr>'+
                                '<tr><td class=\"m_fieldText top\">Comments:</td><td class=\"m_field\"><div style="height:100px;overflow:auto;">'+ comment_t + '</div></td></tr>'+
                                '<tr><td class=\"m_btn\" colspan=\"2\"><button onclick=\"top.setFieldValue(\'feedbackTA\',null);jQuery.nyroModalRemove();\">Ok</button></td></tr>'+
                                '</table></div>'
                });
                fVal.val("");

            },"text"
      );

      top.setFieldValue('feedbackTA',null);
      setTimeout("jQuery.nyroModalRemove();",10000);

  }/* , */
};

/*Create new instance of siteSpace as a global constant namespace <script>alert('test');</script>*/
SITE    = new siteSpace();

SITE.loadTimestamp = new Date();

/*Callback handler from Flash movies.*/
function Flash_Event(obj) {
    if (obj) {
        switch (obj.event) {
            case "actionClick":
                // Check for ad id...if not, use supplied URL.
                if (obj.bannerid && SITE.ads && SITE.ads.banners[obj.bannerid]) {
                    SITE.ads.handleAdClick(obj.bannerid);
                } else if (obj.url) {
                    window.open(obj.url);
                }
            break;
        }
    }
}



function updateSubject(m) {
  if(m == 1 || m == 2){ jQuery("#req_0").css("display","inline"); jQuery("#req_1").css("display","inline"); }
  else if(m == 3){jQuery("#email").addClass("isValidEmail"); jQuery("#req_0").css("display","none"); jQuery("#req_1").css("display","none");}
  else if(m == 4){jQuery("#email").addClass("isValidEmail"); jQuery("#req_0").css("display","none"); jQuery("#req_1").css("display","inline"); }
  else if(m == 5 || m == 6 ||  m == 7){jQuery("#email").addClass("isValidEmail"); jQuery("#req_0").css("display","none"); jQuery("#req_1").css("display","inline"); }
  else{ jQuery("#req_0").css("display","none"); jQuery("#req_1").css("display","none"); }
}

function setFBoptions(){
    var fb_Subject=new Array();
    var o = "";
    fb_Subject[0]=["Just Sayi'n|Feedback [General]","Freeking AWESOME!|Feedback [General Praise]","Pass It On.|Feedback [General Distribute]"];
    fb_Subject[1]=["Question|Feedback [Marketing Question]", "Request Info|Feedback [Marketing Request Info]", "General Comment|Feedback [General Marketing]"];
    fb_Subject[2]=["Info Request|Feedback [Partners Info]", "Contact Me|Feedback [Partner Contact]", "Comments|Feedback [General Partners]"];
    fb_Subject[3]=["Please Contact Me| Sales [Sale WWW Inquiry]"];
    fb_Subject[4]=["A Few Comments|Feedback [General Radio]", "Request Song or Artist|Feedback [Radio Requests]", "Yo DJs|Feedback [Radio DJs]"];
    fb_Subject[5]=["Problem with Recording or Artist Info|Feedback [Radio Recording or Artist Issue]", "Why?|Feedback [Radio Question]"];
    fb_Subject[6]=["HELP!!! |Feedback [Help]", "Web Player|Feedback [Web Player]", "Comments|Feedback [General Support]", "Slacker Music Service|Feedback Support Service]"];
    fb_Subject[7]=["Just a thought|Feedback [Web Player]", "Somethi'n is Broke|[Webmaster Site Error]", "Web Player|Feedback [Web Player]", "I think that...|Feedback [General Web]"];

  for (i=0; i<fb_Subject.length; i++){
    var v = fb_Subject[i];
    for (k=0; k < v.length; k++){
        var x = v[k].split("|");
        o+=  '<option class="sub_'+i+'" value="'+x[1]+'">'+x[0]+'</option>\n';
     }
  }
    return o;
}


/*
    $(document).ready(function(){
        makeSublist('parentID','childID', true, 'selected_val_of_child');
    });

    $(document).ready(function(){
        makeSublist('child','grandson', true, '');
        makeSublist('parent','child', false, '3');
    });

*/
function makeSublist(parent,child,isSubselectOptional,childVal){
  $("body").append("<select style='display:none' id='"+parent+child+"'></select>");
  $('#'+parent+child).html($("#"+child+" option"));

  var parentValue = $('#'+parent).attr('value');
  $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());

  childVal = (typeof childVal == "undefined")? "" : childVal ;
  $("#"+child+' option[@value="'+ childVal +'"]').attr('selected','selected');

  $('#'+parent).change(
    function(){
      var parentValue = $('#'+parent).attr('value');
      $('#'+child).html($("#"+parent+child+" .sub_"+parentValue).clone());
      if(isSubselectOptional)
      $('#'+child).prepend("<option value='none'> -- Select -- </option>");
      $('#'+child).trigger("change");
      $('#'+child).focus();
  });
}


/* TODO: Generalize this function */ /*feedbackArea*/
function setFieldValue(elem, val){
    var text = SITE.FBtext;
    var e = jQuery("#"+elem);
    if(val == false && e.val() == text ){e.val("");}
    else if ( val == true && e.val() == "" ){e.val(text);}
    else if ( val == null  ){e.val(text);}
}

//Things that need to hang off of 'top' for the embedded player
function removeLoader() { try {jQuery("#initLoaderMute").remove() }catch (e) {} }
var secs; var timerID = null; var timerRunning = false; var delay = 1000;
function StopTheClock(){ if(timerRunning){ clearTimeout(timerID); } timerRunning = false; }
function StartTheTimer(){ if (secs==0){ StopTheClock(); tipTimer(); } else{ /*self.status = secs;*/ secs = secs - 1; timerRunning = true; timerID = self.setTimeout("StartTheTimer()", delay); } }



window.onunload = function() {
    // on exit from the homepage, fire the unload beacon
    if (window.location.pathname == "" || window.location.pathname == "/") {
        var unloadTimestamp = new Date();
        var diff = unloadTimestamp - SITE.loadTimestamp;
        SITE.beaconFarts("unload?t=" + diff);
    }
};
