// bfAppObject Class
//****************************************************************************//
// Page Navigation, Shopping basket and music engine
//****************************************************************************//
function bfAppObject( disableajax ) {
  this.basehttp = "http://" + location.host + "/";
  this.xmlhttp = null;
  this.basket;
  this.favmusic;
  this.recentmusic;
  this.currentpage;
  this.noajax = disableajax != null;
  //alert( this.basehttp );

  this.init = function() {
    this.musicinit();
    this.basketinit();
    
    if( !this.noajax && (location.href != this.basehttp) && (location.href.indexOf( '#' ) < 0 ) ) {
      // Prevent creating bfAppObject in places that aren't /index.php
      var extra = location.href.substring( this.basehttp.length );
      location.href = this.basehttp + '#' + extra;
    }

    // Only use AJAX style page transitions if it's supported
    if ( window.XMLHttpRequest || window.ActiveXObject ) {
      this.convertlinks( document );
      
      if( !this.noajax ) {
        // subscribe to unFocus.History and Check for an initial value (deep link).
        unFocus.History.addEventListener('historyChange', this.historyListener);
        var currenthistory = unFocus.History.getCurrent();
        if( currenthistory == "" || currenthistory == "/" ) {
        	// Force history to trigger change by adding ""
        	unFocus.History.addHistory("");
          this.loadPage( this.basehttp );
          //pageTracker._trackPageview('/');
        }else{
          this.historyListener(currenthistory);
        }
      }
    }  
  }
  
  this.deinit = function() {
    // nothing to do.
  }

  // Page Loading
  //****************************************************************************//
  
  this.historyListener = function(historyHash) {
    //alert( historyHash );
    var url = bfapp.basehttp + historyHash;
    
    if( bfapp.currentpage != url ) {
      bfapp.currentpage = url;
      bfapp.changepage( url );
    }
  }
  
  this.changepage = function(url) {
    xmlhttp = getXmlHttpObject();
    if (xmlhttp && !bfapp.noajax ) {
      url += ( url.indexOf( "?" ) < 0 ) ? "?" : "&";
      url += "content=body";
      xmlhttp.onreadystatechange = bfapp.pageLoaded;
      xmlhttp.open("GET",url,true);
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded" );
      xmlhttp.send( "" );
    }else{
      // fall back to using normal request
      window.location = url;
    }
  }
  
  this.loadPage = function(url) {
    if( !bfapp.noajax ) {
      var urlRel = url.substr( this.basehttp.length );
      if( urlRel == '' ) urlRel = '/';
      unFocus.History.addHistory(urlRel);
      // Notify Google Analytics of page change
      if( window.pageTracker ) {
      	pageTracker._trackPageview(urlRel);
     	}
    }else{
      url += ( url.indexOf( "?" ) < 0 ) ? "?" : "&";
      url += "noajax";
      window.location = url;
    }
  }

  this.reloadPage = function() {
    if( !bfapp.noajax ) {
      this.changepage( this.currentpage );
    }else{
      window.location.replace( window.location );
    }
  }

  this.pageLoaded = function() {
    if (xmlhttp.readyState==4) {
      // Response Loaded
      if (xmlhttp.status==200) {
        // Valid Response from Server
        //messages = xmlhttp.responseXML.getElementsByTagName("message");
        var sitebody = getObjectRef( "sitebody" );
        sitebody.innerHTML = xmlhttp.responseText;
        bfapp.convertlinks( sitebody );
        var js = getObjectRef( "js" );
        //if( js ) alert( js.innerHTML );
        if( js ) eval( js.innerHTML );
      }else{
        // Bad response from server
        //alert( "Roaar - Unable to load new page.\nIf the problem persists, let BearFaced know by emailing admin@bearfacedrecords.com" );
      }
    }
  }
  
  this.submitform = function( formobj, url ) {
    xmlhttp = getXmlHttpObject();
    if (xmlhttp && !bfapp.noajax ) {
      var reqstr = collectRequestStrings( formobj );
      //alert( reqstr );
      url += ( url.indexOf( "?" ) < 0 ) ? "?" : "&";
      url += "content=body";
      xmlhttp.onreadystatechange = bfapp.pageLoaded;
      xmlhttp.open("POST",url,true);
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded" );
      xmlhttp.send( reqstr );
    }else{
      // fall back to using normal request
      formobj.submit();
    }
  }
  
  // Links Converstion
  //****************************************************************************//
  this.convertlinks = function( parent ) {
    var links = parent.getElementsByTagName('a');
    for (var i=0; i<links.length; i++) {
      if( links[i].className == 'in' ) {
        var url = links[i].getAttribute('href');
        links[i].setAttribute('href', "javascript:bfapp.loadPage( '"+url.replace(/\%/, "%25")+"' );" );
        links[i].className = "internal";
      }
    }
  }  
  
  // Basket Methods
  //****************************************************************************//
  
  this.basketinit = function() {
    var basketcookie = get_cookie( "basket" );
    if( basketcookie ) {
      this.basket = basketcookie.split( ';' );
    }else{
      this.basket = new Array();
    }
  }
  
  this.basketsize = function() {
    var bs = 0;
    for( var i=0; i< this.basket.length; i++ ) {
      var itemarr = this.basket[i].split(',');
      bs += parseInt(itemarr[1]);
    }
    return bs;
  }
  
  this.updatebasketdisplay = function() {
    var basketsize = getObjectRef( "basketsize" );
    var basketsizes = getObjectRef( "basketsizes" );
    var bs = this.basketsize();
    basketsize.innerHTML = bs;
    basketsizes.innerHTML = s(bs);
  }

  this.buybooty = function( mid ) {
  	var opt = "-";
    var optionbox = getObjectRef( "opt"+mid );
    if( optionbox != null ) opt = optionbox.value;

    var qty = 1.0;
    for( var i=0; i< this.basket.length; i++ ) {
      var itemarr = this.basket[i].split(',');
      if( itemarr[0] == mid && itemarr[2] == opt) {
        qty += parseInt(itemarr[1]);
        this.basket.splice(i,1);
        break;
      }
    }
    var newitem = mid + "," + qty + "," + opt;
    this.basket.unshift( newitem );
    set_cookie( "basket", this.basket.join(';'), 999 );
    this.updatebasketdisplay();
    shownotice();
  }

  this.removebooty = function( mid, opt ) {
    var qty = -1.0;
    for( var i=0; i< this.basket.length; i++ ) {
      var itemarr = this.basket[i].split(',');
      if( itemarr[0] == mid && itemarr[2] == opt ) {
        qty += parseInt(itemarr[1]);
        if( qty > 0 ) {
          this.basket[i] = mid + "," + qty + "," + opt;
        }else{
          this.basket.splice(i,1);
        };
        break;
      }
    }
    if( this.basket.length >0 ) {
      set_cookie( "basket", this.basket.join(';'), 999 );
    }else{
      delete_cookie( "basket" );
    }
    this.updatebasketdisplay();
  } 
  
  // Music Methods
  //****************************************************************************//
  
  this.musicinit = function() {
  	/*
    var favmusiccookie = get_cookie( "favmusic" );
    if( favmusiccookie ) {
      this.favmusic = favmusiccookie.split( ';' );
    }else{
      this.favmusic = new Array();
    }

    var recentmusiccookie = get_cookie( "recentmusic" );
    if( recentmusiccookie ) {
      this.recentmusic = recentmusiccookie.split( ';' );
    }else{
      this.recentmusic = new Array();
    }
    */
  }
  
  this.audioLoad = function( url ) {
    var fp = getObjectRef("bfaudio");
    fp.SetVariable("method:setUrl", url);
  }
  
  this.audioPlay = function() {
    var fp = getObjectRef("bfaudio");
    fp.SetVariable("method:play", "");
  }
  
  this.audioPause = function() {
    var fp = getObjectRef("bfaudio");
    fp.SetVariable("method:pause", "");
  }
  
  this.audioStop = function() {
    var fp = getObjectRef("bfaudio");
    fp.SetVariable("method:stop", "");
  }

  this.audioToggle = function() {
  	var isPlaying = (this.isPlaying == "true");
  	if( isPlaying ) {
  		this.audioPause();
  	}else{
  		this.audioPlay();
  	}
  }  
  
  this.changeTrack = function( url, artist, track ) {
    this.audioLoad(url);
    this.audioPlay();
		getObjectRef("audioline1").innerHTML = (artist == 'undefined') ? "" : artist;
		getObjectRef("audioline2").innerHTML = (track == 'undefined') ? "Playing" : track;
  }
  
  this.onInit = function() {
  	this.position = 0;
  }
  
  this.onUpdate = function() {
  	var isPlaying = (this.isPlaying == "true");
		getObjectRef("audiocd").src = this.basehttp + "images/icons/cd." + (isPlaying ? "gif" : "png");
  }

  // Calender
  //****************************************************************************//
  this.OpenCalender = function(pass) {
    window.open(this.basehttp+'cal?'+pass,'Calender','width=250, height=250, resizable=no, scrollbars=no, toolbar=no, location=no, directories=no, menubar=no') 
  }  
}

// Generic Utility Static methods
//****************************************************************************//

function getObjectRef(name) {
  if(document.getElementById) return document.getElementById(name);
  else if(document.all) return document.all[name];
  else return null;
}

// Cross platform opacity getter
function getOpacity( el ) {
  if( el.bfopacity ) {
    return el.bfopacity;
  }else{
    el.bfopacity = 100;
    return 100;
  }
}

// Cross platform opacity setter
function setOpacity( el, alpha ) {
  el.bfopacity = alpha;
  el.style.filter = "alpha (opacity=" + alpha + ")";
  el.style.mozOpacity = alpha/100;
  el.style.opacity = alpha/100;
}

function getSrc( e ) {
  if(document.all) {
    return window.event.srcElement;
  }
  return e.target;
}

// For pluralising words
function s( num ) {
  return (num==1)? '':'s';
}

function collectRequestStrings( obj ) {
  var reqstr = "";
  for (var i=0; i<obj.childNodes.length; i++) {
    var child = obj.childNodes[i];
    if( child.tagName ) {
      if (child.tagName.toLowerCase() == "input") {
        if (child.type == "text" || child.type == "hidden") {
           reqstr += child.name + "=" + encodeURIComponent(child.value) + "&";
        }else if (child.type == "checkbox") {
           if (child.checked) {
           	 if( reqstr.indexOf(child.name) >= 0 )
           	 {
           	 	 reqstr = reqstr.replace(child.name+"=", child.name+"="+encodeURIComponent(child.value)+",");
           	 }else{
              reqstr += child.name + "=" + encodeURIComponent(child.value) + "&";
             }
           }
        }else if (child.type == "radio") {
           if (child.checked) {
              reqstr += child.name + "=" + encodeURIComponent(child.value) + "&";
           }
        }
      }else if (child.tagName.toLowerCase() == "select") {
        reqstr += child.name + "=" + encodeURIComponent(child.options[child.selectedIndex].value) + "&";
      }else if (child.tagName.toLowerCase() == "textarea" ) {
        reqstr += child.name + "=" + encodeURIComponent(child.value) + "&";
      }else if (child.tagName.toLowerCase() == "div" ) {
        reqstr += collectRequestStrings( child );
      }
    }
  }
  return reqstr;
}

// RSS
//****************************************************************************//

function set_page_rss( url ) {
/*
  var i, a;
  alert( url );
  
  // For each link element
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if( a.getAttribute("type") == "application/rss+xml" ) {
      // Specifying alternate rss view
      a.href = "http://stevenlovegrove.f2s.com/tagged/?filter=image&view=rss";//url;
      alert( a.getAttribute("href") );
    }
  }
*/
}

// Cookies
//****************************************************************************//

function set_cookie ( name, value, exp_days, path, domain, secure ) {
  var cookie_string = name + "=" + escape ( value );
  if ( exp_days ) {
    var expires = new Date ( );
    expires.setDate( expires.getDate() + exp_days );
    cookie_string += "; expires=" + expires.toGMTString();
  }
  if ( path ) {
    cookie_string += "; path=" + escape ( path );
  }else{
    cookie_string += "; path=/";
  }
  if ( domain ) cookie_string += "; domain=" + escape ( domain );
  if ( secure ) cookie_string += "; secure";
  document.cookie = cookie_string;
}

function delete_cookie ( cookie_name ) {
  set_cookie( cookie_name, '', -100 );
}

function get_cookie ( cookie_name ) {
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
  if ( results ) return ( unescape ( results[1] ) );
  return null;
}

// AJAX Page Loading()
//****************************************************************************//

function getXmlHttpObject() {
  var xmlhttp;
  if (window.XMLHttpRequest) {      // Mozilla / Netscape
    xmlhttp=new XMLHttpRequest();
  }else if (window.ActiveXObject) { // Internet Explorer
    xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
  }else{
    xmlhttp=false;
  }
  return xmlhttp;
}

// Audio
//****************************************************************************//

function arrIndexOf( arr, val ) {
  for( var i=0; i< arr.length; i++ ) {
    if( arr[i] == val ) return i;
  }
  return -1;
}

function trackLink( info ) {
  var ar = info.split(',');
  var html =
  '<div class="track">♫ '+
  '<a class="in" href="http://stevenlovegrove.f2s.com/'+ar[0]+'/">' + ar[0] + '</a> - '+
  '<a class="in" href="http://stevenlovegrove.f2s.com/'+ar[0]+'/'+ar[1]+'"/>' + ar[1] + '</a> - '+
  '<a href="javascript:bfapp.changeTrack(\''+ar[0]+'\',\''+ar[1]+'\',\''+ar[2]+'\',\''+ar[3]+'\')">' + ar[2] + '</a> '+
  '<a href="javascript:bfapp.favTrack(\''+ar[0]+'\',\''+ar[1]+'\',\''+ar[2]+'\',\''+ar[3]+'\')"><img src="http://stevenlovegrove.f2s.com/nfav.gif"/></a>'+
  '</div>';
  return html;
}

// Basket
//****************************************************************************//
function shownotice() {
	var notice = getObjectRef( "notice" );
	notice.style.display = "block";
}

function closenotice() {
  var notice = getObjectRef( "notice" );
  notice.style.display = "none";
}

// Social Networking
//****************************************************************************//
addthis_pub  = 'stevenlovegrove';

function fbs_click() {
  u=location.href;
  t=document.title;
  window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
  return false;
}
