// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Truncated epapp() object for external site
function eplib() {
  this.isBlank = function (varName) {
    if (typeof(varName)=="undefined" || varName==null || varName=="" || varName==false)
      return true;
    else
      return false;
  }
  this.getCallbackTime = function() {
    var d = new Date();
    var cb = d.getTime();
    return cb;
  }
  this.currentDate = function() {
    var d = new Date();
    return d.getDate();
  }
  this.addPost = function(url, params) {
    var token = "&";
    if(url.search(/\?/)==-1) {
      token = "?";
    }
    return url + token + params;
  }
  this.encodePostParam = function(inputString) {
      inputString = inputString.replace(/\[/g, '-5B-');
      inputString = inputString.replace(/\]/g, '-5D-');
      inputString = inputString.replace(/\(/g, '-28-');
      inputString = inputString.replace(/\)/g, '-29-');

      return inputString;
  }
}

function epapp() {
  this.lib = new eplib();

 this.setParams = function(appParams) {
    var isDev;
    var appName;
    var network;

    for (var i in appParams) {
      if (appParams[i][0]=="development")
        isDev = appParams[i][1];
      else if (appParams[i][0]=="name")
        appName = appParams[i][1];
      else if (appParams[i][0]=="network")
        network = appParams[i][1];
      else if (appParams[i][0]=="rootUrl")
        rootUrl = appParams[i][1];
    }

    if (this.lib.isBlank(isDev))
      isDev = false;
    this.isDev = isDev;
    this.name = appName;
    if (this.isDev)
      this.name += " Development";
    this.network = network;
    this.rootUrl = rootUrl;

    this.trackerTrimLength = this.rootUrl.length-1;
  }

  this.getName = function() { return this.name; }
  this.getNetworkName = function() {
    if (!this.lib.isBlank(this.network)) {
      switch(this.network) {
        case "myspace":
          return "MySpace";
        case "orkut":
          return "Orkut";
        case "hi5":
          return "Hi5";
        default:
          return "Electric Planet";
      }
    }
  }

  this.trackerTrimLength;
  this.pageTracker;
  this.initializeAnalytics = function (pageTracker) {
    this.pageTracker = pageTracker;
    this.pageTracker._initData();
  }
}

  var app = new epapp();
  var appParams = [];

  var urlPieces = document.URL.split("/");
  var devStatus = urlPieces[3];
  var domainNamePieces = urlPieces[2].split(".");
  var domainName = domainNamePieces[1];
  var isDev = false;
  var rootUrl = "http://www.accuable.com:2005/";

  if (devStatus=="matcher-dev" || (!devStatus.search("matcher") && domainName=="accuable")) {
    isDev = true;
    rootUrl = "http://www.accuable.com:2005/";
  }
  appParams.push(["development", isDev]);
  appParams.push(["rootUrl", rootUrl]);
  appParams.push(["name", "animal"]);
  appParams.push(["network", "ep"]);
  app.setParams(appParams);

function confirmDelete(buttonObj, elementId, hideElementId) {
    // var response = confirm("Are you sure you want to delete?");
    showDialog(buttonObj, elementId, hideElementId);

    //if (response==true) {
    //    hideElement(hideElementId);
    //    processForm(buttonObj, elementId);
    //    return false;
    //}
    return false;
}

function showDialog(buttonObj, elementId, hideElementId) {
  var dialogId = elementId + "_dialog";
  $(dialogId).appear();

  return false;
}
function hideDialog(buttonObj, elementId) {
  var dialogId = elementId + "_dialog";
  $(dialogId).fade();

  return false;
}
function toggleDialog(elementId) {
  var dialog = $(elementId);
  dialog.style.display = (dialog.style.display == "block") ? "none" : "block";

  return false;
}

function highlightElement(thisObject, highlightState, highlightColor) {
  if (typeof(highlightColor)=="undefined" || highlightColor == null)
    highlightColor = "#E7F8FF";
  if (typeof(highlightState)=="undefined" || highlightState == null)
    highlightState = 'on';

  if (highlightState == 'off')
    thisObject.style.backgroundColor = 'transparent';
  else
    thisObject.style.backgroundColor = highlightColor;
}

function hideElement(elementId) {
    document.getElementById(elementId).style.display = "none";
}

function showElement(elementId, displayType) {
    if (displayType!="inline") {
        displayType = "block";
    }
    document.getElementById(elementId).style.display = displayType;
}

function processUrlString(urlString) {
    new Ajax.Request(urlString,
                     { method:'get',
                             onSuccess: serverResponse,
                             onFailure: function (response) {
                             alert("Ajax call failed.");
                         }
                     });

}

function getFormChildren(node, elementsArray, urlArray) {
    for (var i=0; i<node.childNodes.length; i++) {
        var child = node.childNodes[i];
        getFormChildren(child, elementsArray, urlArray);

        j = elementsArray.length;
        if(child.nodeName == 'INPUT') {
            if(child.name == 'action') {
                urlArray[0] = child.value;
            } else if(child.type == 'submit' || child.type == 'image') {
                continue;
            } else if(child.type == 'radio' || child.type == 'checkbox') {
                if (child.checked) {
                    elementsArray[j] = child.name+"="+child.value;
                }
            } else {
                elementsArray[j] = child.name+"="+child.value;
            }
        } else if(child.nodeName == 'SELECT') {
            elementsArray[j] = child.name+"="+child.options[child.selectedIndex].value;
        } else if(child.nodeName == 'TEXTAREA') {
            elementsArray[j] = child.name+"="+child.value;
        }
    }
}

function processForm(buttonObj, formId) {
    var form = document.getElementById(formId);
    var elementsArray = new Array();
    var j=0;
    var urlArray = new Array();
    getFormChildren(form, elementsArray, urlArray);
    var url = urlArray[0];
    j = elementsArray.length;
    elementsArray[j] = buttonObj.name+"="+buttonObj.value;
    var formParams = '';

    for (i=0; i<elementsArray.length; i++) {
        formParams += elementsArray[i];
        if (i<(elementsArray.length-1)) {
            formParams += "&";
        }
    }

    new Ajax.Request(url,
                     { method:'post',
                       parameters: formParams,
                       onSuccess: serverResponse,
                       onFailure: function (response) {
                       alert("Ajax call failed.");
                      }
                     });

    return false;
}

function get_provinces(country_selector_id, type, url){
    var countrySelector = document.getElementById(country_selector_id);
    var countryIndex = countrySelector.selectedIndex;
    var countryId = countrySelector.options[countryIndex].value;

    var zipLabel = document.getElementById('zip_label');
    if (countryId == 5) {
      zipLabel.innerHTML = 'ZIP';
    } else {
      zipLabel.innerHTML = 'Postal Code';
    }

   var urltopost = url+'?type='+type+'&id='+countryId;

    processUrlString(urltopost);
    return false;
}

function extractBlockByTag(inputString, tagName) {
    var results = new Array();
    results[0] = new Array();

    var closeLength = tagName.length + 3;
    var startsAt = inputString.indexOf("<"+tagName);
    var endsAt = inputString.indexOf("</"+tagName+">")+closeLength;
    var tagBlock = false;
    var payload = inputString;
    results[0][0] = tagBlock;
    results[1] = payload;

    var i=0;
    while (startsAt>=0) {
        tagBlock = payload.slice(startsAt, endsAt);
        payload = payload.replace(tagBlock, "");

        tagBlock = tagBlock.slice(tagBlock.indexOf(">")+1, tagBlock.indexOf("</"));

        results[0][i] = tagBlock;
        results[1] = payload;

        startsAt = payload.indexOf("<"+tagName);
        endsAt = payload.indexOf("</"+tagName+">")+closeLength;
        i++;
    }

    return results;
}

function addElementToHead(inputString, elementType) {
    var headID = document.getElementsByTagName("head")[0];
    var newElement = document.createElement(elementType);
    if (elementType == 'script') {
        newElement.setAttribute("type","text/javascript");
        var isIE = navigator.appVersion.search("MSIE");
        if (isIE) {
            newElement.text = inputString;
        } else {
            var scriptText = document.createTextNode(inputString);
            newElement.appendChild(scriptText);
        }
    } else if (elementType == 'style') {
        newElement.setAttribute("type", "text/css");
        if (newElement.styleSheet) {
            newElement.styleSheet.cssText = inputString;
        } else {
            var styleText = document.createTextNode(inputString);
            newElement.appendChild(styleText);
        }
    }
    headID.appendChild(newElement);
}

function processPayload(payload) {
    var blocks;

    blocks = extractBlockByTag(payload, "style");
    styleBlocks = blocks[0];
    payload = blocks[1];
    if (styleBlocks[0]) {
        for (i=0; i<styleBlocks.length; i++) {
            addElementToHead(styleBlocks[i], "style");
        }
    }

    blocks = extractBlockByTag(payload, "script");
    scriptBlocks = blocks[0];
    payload = blocks[1];
    if (scriptBlocks) {
       for (i=0; i<scriptBlocks.length; i++) {
            addElementToHead(scriptBlocks[i], "script");
        }
    }

    return payload;
}

function functionMap(params) {
  var retval;
  var map = params.shift();
  switch(map) {
  case "friendSelector":
    retval = friendSelector(params[0]);
    break;
  case "writeFriendSelector":
    retval = writeFriendSelector(params[0]);
    break;
  case "clearGiftForm":
    clearGiftForm();
    retval = app.sendEmail(params[0], params[1], params[2]);
    break;
  case "sendEmail":
    retval = app.sendEmail(params[0], params[1], params[2]);
    break;
  case "loadTrickOrTreatPage":
    retval = loadTrickOrTreatPage(params[0]);
    break;
  case "writeTrickOrTreatPage":
    retval = writeTrickOrTreatPage(params[0]);
    break;
  }
  return retval;
}

function serverResponse(response) {
    var error = null;
    if(!error) {
        data = response.responseText;
        if( !data ) {
            data = response;
        }
        if (data.search("redirect:")==0) {
            var dataArray = new Array();
            dataArray = data.split(" ",3);
            var redirectUrl = dataArray[1];
            if (redirectUrl.search("http://")==0) {
                processUrlString(redirectUrl);
            }
        } else if (data.search("location:")==0) {
          var dataArray = new Array();
          dataArray = data.split(" ",3);
          var redirectUrl = dataArray[1];
          if (redirectUrl.search("http://")==0) {
            window.top.location.replace(redirectUrl)
          }
        } else if (data.search("nop:")==0) {
           // nop: no operation
        } else if (data.search("alert:")==0) {
            data = data.replace(/^alert: /,"");
            alert(data);
        } else if (data.search("writediv:")==0) {
            var dataArray = new Array();
            dataArray = data.split(/[\n]/,1)[0].split(/\|/);
            var command = dataArray.shift();
            var writediv = command.split(/ /)[1];
            payload = data.replace(/^writediv: .*/,"");
            document.getElementById(writediv).innerHTML = processPayload(payload);
            if(dataArray.length > 0) {
                functionMap(dataArray);
            }
        } else {
               document.getElementById('page').innerHTML = processPayload(data);
        }
    }
}

//  forum helpers

var DotColors = {
    1:'#000000',
    2:'#fd5a6b',
    3:'#3909cc',
    4:'#b518d6',
    5:'#e72a13',
    6:'#5d9134',
    7:'#f7961c',
    8:'#3393ec',
    9:'#f7ef08',
    10:'#ffffff'
}

var TopicForm = {
  editNewTitle: function(txtField) {
    $('new_topic').innerHTML = (txtField.value.length > 5) ? txtField.value : 'New Topic';
  }
}

var EditForm = {
  // show the form
  init: function(postId) {
    $('edit-post-' + postId + '_spinner').show();
    this.clearReplyId();
  },

  // sets the current post id we're editing
  setReplyId: function(postId) {
    $('edit').setAttribute('post_id', postId.toString());
    $('post_' + postId + '-row').addClassName('editing');
    if($('reply')) $('reply').hide();
  },

  setEditStyle: function(styleId) {
    EditForm.activate_dot(styleId);
  },

  // clears the current post id
  clearReplyId: function() {
    var currentId = this.currentReplyId()
    if(!currentId || currentId == '') return;

    var row = $('post_' + currentId + '-row');
    if(row) row.removeClassName('editing');
    $('edit').setAttribute('post_id', '');
  },

  // gets the current post id we're editing
  currentReplyId: function() {
    return $('edit').getAttribute('post_id');
  },

  // checks whether we're editing this post already
  isEditing: function(postId) {
    if (this.currentReplyId() == postId.toString())
    {
      $('edit').show();
      $('edit_post_body').focus();
      return true;
    }
    return false;
  },

  // close reply, clear current reply id
  cancel: function() {
    this.clearReplyId();
    $('edit').hide()
  },

  activate_dot: function(item) {
    for (i=1; i<=10; i++) {
      $('dot_'+i).setStyle({
        backgroundColor: 'transparent'
      });
    }
    if(item == 9 || item == 10) {
      $('dot_'+item).setStyle({
        backgroundColor: '#333333'
      });
      $('edit_post_body').setStyle({
        backgroundColor: '#333333'
      });
    } else {
      $('dot_'+item).setStyle({
        backgroundColor: '#fffaf1'
      });
      $('edit_post_body').setStyle({
        backgroundColor: '#fffaf1'
      });
    }
    $('edit_style').setValue(item);
    $('edit_post_body').setStyle({
        color: DotColors[item]
    });

  }
}

var ReplyForm = {
  // yes, i use setTimeout for a reason
  init: function() {
    EditForm.cancel();
    $('reply').toggle();
    $('post_body').focus();
    ReplyForm.activate_dot($F('reply_style'));
    // for Safari which is sometime weird
//    setTimeout('$(\"post_body\").focus();',50);
    },

  activate_dot: function(item) {
    for (i=1; i<=10; i++) {
      $('dot_'+i).setStyle({
        backgroundColor: 'transparent'
      });
    }
    if(item == 9 || item == 10) {
      $('dot_'+item).setStyle({
        backgroundColor: '#333333'
      });
      $('post_body').setStyle({
        backgroundColor: '#333333'
      });
    } else {
      $('dot_'+item).setStyle({
        backgroundColor: '#fffaf1'
      });
      $('post_body').setStyle({
        backgroundColor: '#fffaf1'
      });
    }
    $('reply_style').setValue(item);
    $('post_body').setStyle({
        color: DotColors[item]
    });

 }

}

var GiveForm = {
  // show the form
  init: function() {
    $('give_spinner').show();
    this.clearStudentId();
  },

  // sets the current student id we're giving to
  setStudentId: function(studentId) {
    $('gift').setAttribute('student_id', studentId.toString());
  },

  // clears the current post id
  clearStudentId: function() {
    var currentId = this.currentStudentId()
  },

  // gets the current post id we're editing
  currentStudentId: function() {
    return $('gift').getAttribute('student_id');
  },

  // checks whether we're editing this post already
  isGiving: function(studentId) {
    if (this.currentStudentId() == studentId.toString())
    {
      $('gift').show();
      //      $('edit_post_body').focus();
      return true;
    }
    return false;
  },

  // close reply, clear current reply id
  cancel: function() {
    this.clearStudentId();
    $('gift').hide()
  }
}

/* ---------------------------------------------------------*/
var PWCPeriodicalExecuter = Class.create({
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  execute: function() {
    this.callback(this);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
/*        this.currentlyExecuting = true; */ /* PWC */
      }
    }
  }
});

Abstract.PWCTimedObserver = Class.create(PWCPeriodicalExecuter, {
  initialize: function($super, form_element, frequency, callback) {
    $super(callback, frequency);
    this.form_element   = $(form_element);
    this.lastValue = this.getValue();
  },

  execute: function() {
    var value = this.getValue();
    if (Object.isString(this.lastValue) && Object.isString(value) ?
        this.lastValue != value : String(this.lastValue) != String(value)) {
      this.callback(this, value);
      this.lastValue = value;
    } else {
      this.currentlyExecuting = false;
    }
  }
});

/* callback is asynchronous, needs onComplete callback to set currentlyExecuting to false */

Form.Element.PWCObserver = Class.create(Abstract.PWCTimedObserver, {
  getValue: function() {
    return Form.Element.getValue(this.form_element);
  }
});
