//
//  File:       application.js
//
//  Synopsis:   Main entry point for application
//
//----------------------------------------------------------------------------

// Set up our namespace
var vinomis = new Object();

// Global app object
theApp = null;

//
// Cross-browser solution for triggering init after the page loads but before
// external resources (e.g. images) are loaded.  From http://dean.edwards.name/weblog/2006/06/again/.
//
function init() {
  // Quit if this function has already been called
  if (arguments.callee.done)
    return;
  
  // Flag this function so we don't do the same thing twice
  arguments.callee.done = true;
  
  // kill the timer
  if (_timer)
  {
    clearInterval(_timer);
    _timer = null;
  }


  // Create the app and get things rolling
  theApp = new vinomis.App();
};

/* For Mozilla */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* For Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  var dummy = location.protocol == "https:" ? "https://javascript:void(0)" : "javascript:void(0)";
  document.write("<script id=__ie_onload defer src='" + dummy + "'><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* For Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

function verifyRequired() {
  if (document.icpsignup["fields_email"].value == "") {
    document.icpsignup["fields_email"].focus();
    alert("The Email field is required.");
    return false;
  }
return true;
}

function window_onload()
{
  if (theApp)
    theApp.debugTimer.log("window.onload");

  init();
}

/* For other browsers */
window.onload = window_onload;

//
// This is overridden for the html integration script but just use Prototype's Ajax directly here
//
vinomis.Ajax = Ajax;


//----------------------------------------------------------------------------
//
// vinomis.App class
//
//----------------------------------------------------------------------------

vinomis.App = Class.create();

vinomis.App.prototype = {

  // Initialize
  initialize: function() {
    // Member variables
    this.debugTimer = new vinomis.DebugTimer();
    this.lastOpenSongExpando = null;
    this.lastOpenCalendarDay = null;
    this.lastOpenContactImporterExpando = null;
    this.lastOpenFeedExpando = null;
    this.lastOpenMessageReplyExpando = null;
    this.nameThatTune = null;
    this.artistOnTour = null;
    this.data = (typeof(g_data) != "undefined") ? g_data : null;
    this.baseUrl = (typeof(g_baseUrl) != "undefined") ? g_baseUrl : "/";
    this.facebookBaseUrl = (typeof(g_facebookBaseUrl) != "undefined") ? g_facebookBaseUrl : "/";
    this.swfBaseUrl = (typeof(g_swfBaseUrl) != "undefined") ? g_swfBaseUrl : this.baseUrl + 'swfs/';
    this.swfVersion = (typeof(g_swfVersion) != "undefined") ? g_swfVersion : Math.random();

    // Set up the theApp global so that it's available to any classes that get
    // created in the initialize
    theApp = this;

    this.debugTimer.log("initialize javascript app");

    this.iContactResult = getQueryVariable('iContact');

    if ('success' == this.iContactResult) {
        Cookie.set('iContact', 'success', 1000);
    }    
    
    this.showLoginOverlay = (Cookie.get('iContact') == null);
    
    if (document.referrer.indexOf('http://www.vinomis.com') == -1) {
      this.showLoginOverlay = false;
    }      
 
 
    if ('failed' == this.iContactResult) {
      alert('Invalid email address');
      this.showLoginOverlay = true;
    }
    
     
    // Hook up login link to open the login dialog
    if (this.showLoginOverlay)
    {
      this.debugTimer.log("-- create LoginDialog class");
      vinomis.LoginDialog.instance = new vinomis.LoginDialog();
      vinomis.LoginDialog.instance.showDialog();
      this.debugTimer.end("-- create LoginDialog class");
    }

      var baseUrl = document.URL
      var index = baseUrl.indexOf('?')
      if (index > -1) {
        baseUrl = baseUrl.substring(0,index)
      }
      
      $('redirect').value = baseUrl + '?icontact=success'
      $('errorredirect').value = baseUrl + '?icontact=failure'
 
    // Set focus on account page (login dialog handles focus itself)
    if ($('login_password') && !$('login_dialog'))
    {
      this.debugTimer.log("-- create SetLoginFocus");
      function setFocus()
      {
        if ($('login_email').value == "")
          $('login_email').focus();
        else
          $('login_password').focus();
      }
      setTimeout(setFocus, 1);
      this.debugTimer.end("-- create SetLoginFocus");
    }

  },

  adjustHeight: function() {
    // Do nothing; for compatibility with theApp object in OpenSocial        
  },
  
  createObjectsFromData: function(c, list, name) {
    this.debugTimer.log("-- create " + list.length + " instances of " + name);

    // Create a simulated hash table of instances for fast lookups
    if (!c.hash)
      c.hash = new Array;

    if (!c.arr)
      c.arr = new Array;

    // Create instances of the specified class for each item in the list.  Items must have an id.
    for (var i = 0; i < list.length; i++)
    {
      var o = new c(list[i].id, list[i].tag);
      c.arr.push(o);
      c.hash[list[i].id] = o;
    }

    // Add a helper function "byId" for use when wiring up onclick event handlers
    if (!c.byId)
      c.byId = function(id) { return c.hash[id]; }

    this.debugTimer.end("-- create " + list.length + " instances of " + name);
  },

  ping: function(url) {
    var image = new Image();
    image.src = url;
    image.width = 0;
    image.height = 0;
    document.body.insertBefore(image, document.body.firstChild);
  },

  removeObjectsById: function(c, list) {
    // nothing to do if the target object does not have any data stored
    if(!c.hash || !c.arr) {
      return;
    }

    removed = {};
    for(var i = 0; i < list.length; ++i) {
      var o = c.byId(list[i]);
      if(o) {
        if(o.onRemove) {
          o.onRemove();
        }
        delete c.hash[list[i]];
        removed[list[i]] = 1;
      }
    }
    for(i = 0; i < c.arr.length; ++i) {
      if(removed[c.arr[i].id]) {
        c.arr[i] = null;
      }
    }
    c.arr = c.arr.compact();
  },

  trackEvent: function(path) {
    //alert(path);  // Uncomment for dev/test purposes
    if (typeof(g_urchinAvailable) != "undefined" && g_urchinAvailable)
      urchinTracker(path);
  },

  urlForSwf: function(swf_name) {
    return theApp.swfBaseUrl + swf_name + '?v=' + theApp.swfVersion.toString();
  }
};

var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
}

//----------------------------------------------------------------------------
//
// vinomis.DebugTimer class
//
//----------------------------------------------------------------------------

vinomis.DebugTimer = Class.create();

vinomis.DebugTimer.prototype = {

  // Initialize
  initialize: function() {
    this.times = new Array;
    this.reported = false;
  },

  // Checkpoint an instance in time
  log: function(name, t) {
    if (t == null)
      t = (new Date()).getTime();
    this.times.push({name:name, startTime:t});
    this.times[name] = this.times[this.times.length-1];
  },

  // Stop timing a checkpoint to get a specific duration
  end: function(name, t) {
    if (t == null)
      t = (new Date()).getTime();
    if (this.times[name])
      this.times[name].elapsed = t - this.times[name].startTime;
  },
  
  // Write array of timestamps
  reportCheckpoints: function() {
    var listEl = $('debug_timing_list');
    if (listEl)
    {
      listEl.innerHTML = "";

      // Add HTML parsing times
      if (!this.reported)
      {
        if (typeof(g_debugTimeStart) != "undefined")
          this.log("start parse HTML", g_debugTimeStart);

        if (typeof(g_debugTimeEnd) != "undefined")
          this.log("end parse HTML", g_debugTimeEnd);

        if (typeof(g_debugBrowserSniffStart) != "undefined")
          this.log("start browser sniff", g_debugBrowserSniffStart);

        if (typeof(g_debugBrowserSniffEnd) != "undefined")
          this.log("end browser sniff", g_debugBrowserSniffEnd);
      }

      // Sort array of timestamps
      var times = this.times.sortBy(function(o, i) {return o.startTime + i;});  // add i to get items with the same time in the right order

      function writeRow(s, n, e)
      {
        var row = document.createElement("li");
        row.innerHTML = "<div style='float:left; width:80px;'>" + (s == 0 ? "-" : s) + "</div>";
        row.innerHTML += "<div style='float:left;'>" + n + ((e != null) ? " (" + e + " ms)" : "") + "</div>";
        listEl.appendChild(row);
      }

      // Write array of times
      writeRow("<u>Started</u>", "<u>Checkpoint</u>", null);

      for (var i = 0; i < times.length; i++)
        writeRow((times[i].startTime - times[0].startTime), times[i].name, times[i].elapsed);

      this.reported = true;
    }
  }
};


//----------------------------------------------------------------------------
//
// vinomis.LoginDialog class
//
//----------------------------------------------------------------------------

vinomis.LoginDialog = Class.create();

vinomis.LoginDialog.prototype = {

  initialize: function(prefix) {
    this.prefix = prefix || 'login';
    this.dialog = $(this.prefix + '_dialog');
    
    // Observe events on the sign in link and overlay
    Event.observe(this.dialog, 'keypress', this.onKeyPress.bind(this), false);
    if ($(this.prefix + '_close')) Event.observe(this.prefix + '_close', 'click', this.onClickClose.bind(this), false);
  },

  onClickClose: function(ev) {
    this.hideDialog();
    Event.stop(ev);
  },

  showDialog : function() {
     // Observe close clicks
//    Event.observe('login_overlay', 'mousedown', this.hideDialog.bind(this), false);

      // Compute new positions
    var scrollOffsets = document.viewport.getScrollOffsets();
    var dialogStyle = {};
    dialogStyle.top = "0px"; //"" + ([document.viewport.getHeight() - this.dialog.getHeight(), 125].min() + scrollOffsets[1]) + "px";
    dialogStyle.left = "" + ((document.body.offsetWidth - this.dialog.getWidth())/2) + "px";
    this.dialog.setStyle(dialogStyle);
    $('login_overlay').style.height = get_overlay_height();

    // Display sign-in form and overlay div
    this.dialog.show();
    $('login_overlay').show();
    
    window.onscroll = function(){
      $('login_overlay').style.height = get_overlay_height();
    }
    
    if ($(this.prefix + '_email')) {
      // Set focus to email field
      setTimeout(function() {$(this.prefix + '_email').focus();}.bind(this), 1);
    }

  },
  
  
  onClickLogin: function(ev) {
    this.showDialog();
    
    if (ev) {
      Event.stop(ev);
    }
  },
  
  onKeyPress: function(ev) {
    var esc = window.event ? 27 : ev.DOM_VK_ESCAPE;
    var key = window.event ? event.keyCode : ev.keyCode;
    if (key == esc)
      this.hideDialog();
  },

  hideDialog: function() {
    this.dialog.hide();
    $('login_overlay').hide();
    Cookie.set('iContact', 'declined', 14);
  }

};

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;}


function get_overlay_height() {
  // Return the new style attribute for the login overlay by calculating the
  // height of the viewing area, adding the scroll offset, and appending 'px'
  overlay_height = document.viewport.getHeight()+document.viewport.getScrollOffsets()[1];
  overlay_height = [overlay_height, 10000].max();
  return ''+overlay_height+'px';
}

function getScrollY() {
  var y = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    y = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    y = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    y = document.documentElement.scrollTop;

  }
  return y;
}

function reportABSuccess(exp_id,var_id)
{
  new Ajax.Request(theApp.baseUrl + 'ab_arbiter',
  {
    method:'get',
    parameters: {'exp_id': exp_id, 'variant_id': var_id }
  });
}

var ping = function(url) {
  theApp.ping(url);
}

//Exit function
    var areYouReallySure = false;
    var internalLink = false;
    function areYouSure() {
    if (!areYouReallySure) {
    areYouReallySure = true;
    location.href="EditCartSubmit.do?prodId=38&cart=true"
    return "*****************************************************\n\nWait!   \n\nBefore you leave , please take a look at this limited time offer. Remember, this is a FREE trial! \n\nWhy miss the chance to Stop the Aging Process to your body?\n\n Click CANCEL to get your free trial!\n\n *****************************************************";
    }
    }

//End Exit function

//Page functions
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function switchMenu(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
}

function verifyRequired() {
  if (document.icpsignup["fields_email"].value == "") {
    document.icpsignup["fields_email"].focus();
    alert("The Email field is required.");
    return false;
  }
  
return true;
}
//End Page functions
