var serviceURL = 'http://cownter.cownt.us/';   // URL of the Cowrate service
var SESSIONPERSISTANCE = 2880; // amount of minutes that the session cookie remains in the browser
var IMGCOMPLETEINTERVAL = 100; // interval checking if image completed downloading, ms
var VERSION = 1.1;              // version of the cowrate protocol
var container;                     // the box with thumbs up and thumbs down
window.cowrate_bubbleState = 'ON'; // bubbles are on by default, global to avoid reading cookie all the time
// window.cowntus_token is the the only exterval variable for cowrate

// add css that defines look of the bubble
document.write('<link rel="stylesheet" type="text/css" href="http://cownt.us/cowrate.css" />');

// add load and unload events
addLoadEvent(cr_preparePage);
addBeforeUnloadEvent(cr_cleanupPage);
addUnloadEvent(cr_cleanupPage);

function cr_cleanupPage() {
    if (window.cowrate_num_img_interval){
       clearInterval (window.cowrate_num_img_interval);
    }
}
// executes onLoad 
function cr_preparePage() {

    var myurl = window.location.toString().replace(/https?:\/\//,'');
    window.cowrate_curr_key = encodeURIComponent(encodeURIComponent(myurl));
    
    // This is the only error you should see from the cowrate javascript. 
    // you need to provide a token that was given to you 
    // when you signed up. Visit http://cowntus.com for info.
    if ( ! window.cowntus_token){
      alert ("Cowrate requires a cowntus_token token to work. Visit cownt.us for info.");
    }
    
    // add arrows
    container = document.createElement('div');
    container.setAttribute("id", "dock");


    // show button in OFF position if user turned bubbles off
    if ( window.cowrate_bubbleState == 'OFF' || readCookie("cowrateBubbleState") == 'OFF' ){
       window.cowrate_bubbleState = 'OFF';
       var cowrateImg;
       if ( cowrateImg = document.getElementById("cowrateState")) {
         cowrateImg.src= "http://cownt.us/images/cowrate-off.png";
       }
    }

    if (window.cowrate_category){
      window.cowrate_UP_img = document.createElement('div');
      window.cowrate_UP_img.setAttribute("id", "cowrate_up");
      window.cowrate_UP_img.onclick = upPage;
      container.appendChild(window.cowrate_UP_img);

      window.cowrate_NUM_img = document.createElement('div');
      window.cowrate_NUM_img.setAttribute("id", "cowrate_number");
      container.appendChild(window.cowrate_NUM_img);

      window.cowrate_DOWN_img = document.createElement('div');
      window.cowrate_DOWN_img.setAttribute("id", "cowrate_down");
      window.cowrate_DOWN_img.onclick = downPage;
      container.appendChild(window.cowrate_DOWN_img); 
     
      if (window.cowrate_bubbleState == 'ON'){
        document.body.appendChild(container);
      }
    }

    // increment page cowrate on the server, to count visitors
    cr_incrPage();

}

//
// 3 functions that call the server by requesting images
//
function cr_incrPage() {
    // generate sid if we do not have one
    if ( ! window.cowrate_sid ){ 
      var sid  = readCookie("cowrateSid");
      if ( ! sid ){
        sid = generateSid();
        setCookie("cowrateSid",sid,SESSIONPERSISTANCE);
      }
      // cannot pass args to interval/callback functions so set globals
      window.cowrate_sid = sid;
    }

    // if no cownter_title given, pull it from the page
    if ( typeof window.cowrate_title=='undefined') {
        window.cowrate_title = document.title;
    }

    var req = serviceURL + VERSION + '/cr_incr/'+ window.cowrate_curr_key + '/' + window.cowrate_title + '/' + window.cowrate_category + '/' + window.cowrate_sid + '/' + window.cowntus_token + '/' + generateSid();
    window.cowrate_incr_img = null;
    window.cowrate_incr_img = new Image();
    window.cowrate_incr_img.src = req;

    // Display the rating
    window.cowrate_num_img_interval = setInterval(displayRating,IMGCOMPLETEINTERVAL);
}

function displayRating() {
    if(window.cowrate_incr_img.complete){
       clearInterval (window.cowrate_num_img_interval);
       var count = null;
       if ( window.cowrate_incr_img.height == 3 ){
          count = '-';
       }else if( window.cowrate_incr_img.height == 2){
          count = 0;
       }else{
          count = window.cowrate_incr_img.width;
       }
       window.cowrate_NUM_img.innerHTML = count;
    }
}

function upPage() {
    var req  = serviceURL + VERSION + '/cr_up/' + window.cowrate_curr_key + '/' + window.cowrate_category + '/' + window.cowrate_sid + '/' + window.cowntus_token + '/' + generateSid();
    window.cowrate_up_img = null;
    window.cowrate_up_img = new Image();
    window.cowrate_up_img.src = req;
    cr_incrPage();
}

function downPage() {
    var req  = serviceURL + VERSION + '/cr_down/' + window.cowrate_curr_key + '/' + window.cowrate_category + '/' + window.cowrate_sid + '/' + window.cowntus_token + '/' + generateSid();
    window.cowrate_down_img = null;
    window.cowrate_down_img = new Image();
    window.cowrate_down_img.src = req;
    cr_incrPage();
}



// generates "unique enough" session id 
function generateSid(){
      var now = new Date();
      var rnum = ''+now.getHours(); 
      return rnum.concat(now.getMinutes(),now.getSeconds(),now.getMilliseconds(),Math.floor(Math.random() * 10000));
}

// gets called when the button is clicked to turn the bubbles on and off
function CowrateBubbleToggle(e, elem) {
  var xLoc = e.clientX - elem.x;
    if (xLoc > 56) {
        if (window.cowrate_bubbleState == "ON"){
            setCookie("cowrateBubbleState", "OFF")
            window.cowrate_bubbleState = "OFF";
            elem.src = "http://cownt.us/images/cowrate-off.png";
            document.body.removeChild(container);
        } else {
            removeCookie("cowrateBubbleState");
            window.cowrate_bubbleState = "ON";
            elem.src = "http://cownt.us/images/cowrate-on.png";
            document.body.appendChild(container);
        }
    } else {
        document.location = "http://cownt.us/apps.html";
    }
}

// add onLoad callback to the other onLoad events that may be registered
// makes sure to not override current page functionality 
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function addBeforeUnloadEvent(func) {
    var oldonbeforeunload = window.onbeforeunload;
    if (typeof window.onbeforeunload != "function") {
        window.onbeforeunload = func;
    } else {
        window.onbeforeunload = function() {
            if (oldonbeforeunload) {
                oldonbeforeunload();
            }
            func();
        }
    }
}

function addUnloadEvent(func) {
    var oldonunload = window.onunload;
    if (typeof window.onunload != "function") {
        window.onunload = func;
    } else {
        window.onunload = function() {
            if (oldonunload) {
                oldonunload();
            }
            func();
        }
    }
}

//
// generic cookie functions
//
function setCookie(key,value,expMin){
  var expires_date;
  if(expMin){
    var expires = expires * 1000 * 60;
    var d = new Date();
    expires_date = new Date( d.getTime() + (expires) );;
    document.cookie=key + "=" + escape(value) + "; expires=" +  expires_date.toGMTString() + "; path=/";
  }else{
    document.cookie=key + "=" + escape(value) + "; path=/";
  }
}

function removeCookie(key){
   var cookieDate = new Date(2000,1,1,1,1,1);
   document.cookie=key + "=; expires=" + cookieDate.toGMTString() + "; path=/";
}

function readCookie(key){
  var cookie = document.cookie;
  var first = cookie.indexOf(key+"=");

  if (first >= 0){
     var str = cookie.substring(first,cookie.length);
     var last = str.indexOf(";");

     if (last < 0) last = str.length;

     str = str.substring(0,last).split("=");
     return unescape(str[1]);

  }else{
     return null;
  }
}


