// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


/*
 * Author: Brent Lintner
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the the MIT License
 * http://www.opensource.org/licenses/mit-license.php
 */
/**
 * @author brent
 * Note: CSS external manipulation still uses prototype for now
 */

/*****************************************************************************
 *	base Class
 *
 *	@title: base
 *
 *	Purpose: base functions
 *
 *****************************************************************************/

function base(){
  this.options = null;
};


//shift a external css rule
base.prototype.shiftCss = function(optionsH){
  this.options = new Hash().merge(optionsH);

  if (this.options.get("from") >= this.options.get("to"))
  {
    this.options.set("direction",0);
  }
  else{
    this.options.set("direction",1);
  }
  this._shiftCss();

};

//sub shift funtion
base.prototype._shiftCss = function(){

  //going up
  if (this.options.get("direction"))
  {
    this.options.set("from",this.options.get("from") + this.options.get("inc"));
    if (this.options.get("from") >= this.options.get("to")){
      this.options.set("from",this.options.get("to"));
      this.setMiscRule(this.options.get("selector"),this.options.get("from"),this.options.get("rule"));
      //console.log(this.options.get("afterFinish").toString().replace(/\n/,"gfdfs"));
      //eval(this.options.get("afterFinish").toString().replace(/\n/,"fsdfsd"));
      this.options = null;
    }
    else{
      this.setMiscRule(this.options.get("selector"),this.options.get("from"),this.options.get("rule"));
      setTimeout(function(){site._shiftCss();},this.options.get("iter"));
    }
  }
  //going down
  else{
    this.options.set("from",this.options.get("from") - this.options.get("inc"));
    if (this.options.get("from") <= this.options.get("to")){
      this.options.set("from",this.options.get("to"));
      this.setMiscRule(this.options.get("selector"),this.options.get("from"),this.options.get("rule"));
      //console.log(this.options.get("afterFinish").toString().replace(/\n/,"ffdf"));
      //eval(this.options.get("afterFinish").toString().replace(/\n/,"fsdfsd"));
      this.options = null;
    }
    else{
      this.setMiscRule(this.options.get("selector"),this.options.get("from"),this.options.get("rule"));
      setTimeout(function(){site._shiftCss();},this.options.get("iter"));
    }
  }
  


  
};

base.prototype.setMiscRule = function(sel,val,rule){
    switch(rule){
      case "opacity": 
	this.setRule(sel, { opacity : val});

      default:
	break;
    }
  };

base.prototype.getRule = function(title){

    var i,x,tempRule,sheet,rules;

    // get style sheet according to title
    for (i = 0; i < document.styleSheets.length; i++) {

      sheet = document.styleSheets[i];
      rules = sheet.cssRules ? sheet.cssRules : sheet.rules;

      for (x = 0; x < rules.length; x++) {
	if (rules[x].selectorText != null) {
	    if (rules[x].selectorText == (String(title))) {
		return rules[x];
	    }
	}
      }
    }

};

base.prototype.setRule = function(selector, styles){
  var i, x, sheet, rules;

  for (x = document.styleSheets.length - 1; 0 <= x ; x--){
    sheet = document.styleSheets[x];
    rules = sheet.cssRules || sheet.rules;

    for (i = rules.length - 1; 0 <= i; i--){
      if (rules[i].selectorText == selector){
	  return Object.extend(rules[i].style, styles);
      }
    }
  }

  var index = rules.length;
  if (sheet.insertRule){ // Normal browsers
    sheet.insertRule(selector + '{ }', index);
  } else { // IE: if (sheet.addRule){
    sheet.addRule(selector, ';', index);
  }

  Object.extend((sheet.cssRules || sheet.rules)[index].style, styles);};

base.prototype.open_window = function(link){
    window.open(link);
};

base.prototype.getBrowserHeight = function(){

  var viewportheight;

  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
  if (typeof window.innerHeight != 'undefined')
  {
    viewportheight = window.innerHeight;
  }

  // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
  else if (typeof document.documentElement != 'undefined'
   && typeof document.documentElement.clientHeight !=
   'undefined' && document.documentElement.clientHeight != 0)
  {
     viewportheight = document.documentElement.clientHeight;
  }

  // older versions of IE
  else
  {
     viewportheight = document.getElementsByTagName('body')[0].clientHeight;
  }


  return(viewportheight);

};

base.prototype.getBrowserWidth = function(){

  var viewportwidth;

  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
  if (typeof window.innerWidth != 'undefined')
  {
    viewportwidth = window.innerWidth;
  }

  // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
  else if (typeof document.documentElement != 'undefined'
   && typeof document.documentElement.clientWidth !=
   'undefined' && document.documentElement.clientWidth != 0)
  {
     viewportwidth = document.documentElement.clientWidth;
  }

  // older versions of IE
  else
  {
     viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
  }


  return(viewportwidth);

};



/*****************************************************************************
 *	ajax Class
 *
 *	@title: ajax
 *
 *	Purpose: used to perform AJAX interactions.
 *
 *****************************************************************************/
function ajax(){

    // Object Properties
    this.ajaxEngaged = false;
    this.xmlHttp = null;
    this.handler = null;
};

ajax.prototype = new base();

ajax.prototype.setRequest = function(scriptURL, formType, formAddData){
    if (this.ajaxEngaged == false) {

        this.xmlHttp = this.getXmlHttpObject();

		//this is set after object creation
        this.xmlHttp.onreadystatechange = this.handler;

        // if form specified was GET
        if (formType.toLowerCase() == "get") {


            // create get request
            if (formAddData == "") {
                this.xmlHttp.open(formType.toLowerCase(), scriptURL, true);
            }
            else {
                this.xmlHttp.open(formType.toLowerCase(), scriptURL + "?" + formAddData, true);
            }

            // IE caching issue fix. will cahce ajax request pages
            this.xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
            this.xmlHttp.setRequestHeader("Cache-Control", "no-cache");
            this.xmlHttp.send(null);


        }

        // if form specified was POST
        else
            if (formType.toLowerCase() == "post") {

                // create post request
                this.xmlHttp.open(formType.toLowerCase(), scriptURL, true);

                //Send the proper header information along with the request
                this.xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
                this.xmlHttp.setRequestHeader("Content-length", formAddData.length);
                this.xmlHttp.setRequestHeader("Connection", "close");
                this.xmlHttp.send(formAddData);


            }
    }

};

ajax.prototype.onUninitialize = function(transport){
};

ajax.prototype.onLoading = function(transport){
};

ajax.prototype.onLoaded = function(transport){
};

ajax.prototype.onInteractive = function(transport){
};

ajax.prototype.onSuccess = function(transport){ };

ajax.prototype.onFailure = function(transport){
};

ajax.prototype.getXmlHttpObject = function(){

    var xmlHttp = null;

    try {
        // Web Standards
        xmlHttp = new XMLHttpRequest();
    }
    catch (e) {
        // Internet Explorer
        try {
            xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
};

ajax.prototype.stateHandler = function(arg){

    switch (this.xmlHttp.readyState) {
      case 0:
	  window.setTimeout("void(0)", 50);
	  this.onUninitialize();
	  break;

      case 1:
	  window.setTimeout("void(0)", 50);
	  this.onLoading();
	  break;

      case 2:
	  window.setTimeout("void(0)", 50);
	  this.onLoaded();
	  break;

      case 3:
	  window.setTimeout("void(0)", 50);
	  this.onInteractive();
	  break;

      case 4:

	  this.ajaxEngaged = false;
	  if (this.xmlHttp.status == 200) {
	      if (this.xmlHttp.getResponseHeader("Content-Type").match(/text\/javascript/)){
		eval(this.xmlHttp.responseText);
	      }else{
	      this.onSuccess(this.xmlHttp);
	      }
	  }
	  else {
	      if (this.xmlHttp.getResponseHeader("Content-Type").match(/text\/javascript/)){
		eval(this.xmlHttp.responseText);
	      }else{
	      this.onFailure();
	      }
	  }

	  return;
    }
};

//keeps "this" from disappearing into the void on ajax state handlers (called currying)
ajax.prototype.create_handler = function(my_this){
    this.handler = function(arg){
        my_this.stateHandler(arg)
    };
};





/*****************************************************************************
 *	Front End ajax custom class extention example
 *
 *	adds one instance specific handlers and functions to ajax shell class
 *****************************************************************************/
function controller(){
    this.ajaxDiv = "main";
    //this.t1 = 0;
    //this.t2 = 0;
    this.lastPopUp = '';
};

controller.prototype = new ajax();

//controller.prototype.startClock = function(){
    //var today = new Date();
    //var h = today.getHours();
    //var m = today.getMinutes();
    //var s = today.getSeconds();
    //var days = today.toDateString();
    ////add a zero in front of numbers<10
    //m = this.checkTime(m);
    //s = this.checkTime(s);
    //document.getElementById('time').innerHTML = days + '  ' + h + ":" + m + ":" + s;
//};

//controller.prototype.checkTime = function(i){
    //if (i < 10) {
        //i = "0" + i;
    //}
    //return i;
//};

controller.prototype.toggleImage = function(bool, obj){
    var popup = document.getElementById('global-popup-image');
    var width;

    
    if (bool) {
        this.lastPopUp = obj;
        popup.firstChild.src = obj.src.replace("medium", "original");
	this.setRule("#global-popup-image",{
	      width: this.getBrowserWidth()+'px'
	    });
	    
	
	//this.setRule("#global",{opacity: 0});

	new Effect.Fade("global",{duration: 0.5,
	  afterFinish: function(){
	    Element.scrollTo('global-popup-image');
	    
	    site.setRule("#global-loadingdiv",{
	      top: '250px',
	      left: site.getBrowserWidth()/2-16+'px',
	      background: 'url(../images/loader.gif) no-repeat'
	      });
	  }
	});
	      
        setTimeout(function(){new Effect.Appear(popup, {
            duration: 0.5,
	    afterFinish: function(){
		site.setRule('#global-loadingdiv', {
		    background: 'url() no-repeat'
		});
	      }});},1000);
        
    }
    else {
	
	site.setRule("#global-loadingdiv",{
	  top: '250px',
	  left: site.getBrowserWidth()/2-16+'px',
	  background: 'url(../images/loader.gif) no-repeat'
	  });
      
        new Effect.Fade(popup, {
            duration: 0.5,
	    afterFinish: function(){
	      //site.setRule("#global",{opacity: 1.0});
	      new Effect.Appear("global",{duration: 0.5,
		beforeStart: function(){
		  site.setRule('#global-loadingdiv', {
		      background: 'url() no-repeat'
		  });
		},
		afterFinish: function(){
		  Effect.ScrollTo(site.lastPopUp,{offset: -100});
		}

	      });
	      document.getElementById('global-popup-image').firstChild.attributes["src"].nodeValue = "";
	    }
        });
    }
};

controller.prototype.toggleLoad = function(bool){
    if (bool) {
	site.setRule("#global-loadingdiv",{
	      top: (window.pageYOffset + 250)+'px',
	      left: site.getBrowserWidth()/2-16+'px',
	      background: 'url(../images/loader.gif) no-repeat'
	      });
	this.setRule("#global",{
	      opacity: 0.1
	    });
	$('global-content-stamp').update('please wait....');
    }
    else {
        this.setRule('#global-loadingdiv', {
            background: 'url() no-repeat'
        });
	this.setRule("#global",{
	      opacity: 1.0
	    });
	$('global-content-stamp').update('');
    }
};

controller.prototype.renderJsView = function(page){


	this.setRule('body', {
        cursor: 'progress'
    });

    //send off a generic request, will be auto evald if js content type
    this.serverCall(page, null, null);
	//new Ajax.Request('/home/'+page, {method: 'get', asynchronous:true, evalScripts:true});
};

controller.prototype.renderView = function(page){

	this.setRule('body', {
        cursor: 'progress'
    });

    this.serverCall(page, function(transport){
        site.setRule('body', {
            cursor: 'default'
        });
        document.getElementById("global-content-main").innerHTML = transport.responseText;
        //site.toggleLoad(false);
    }, null);
};

controller.prototype.serverCall = function(calling, success, failure){

    //this.toggleLoad(true);

    //clear the endless page event observer if active
    if (endlessTimeOut != false){
      clearTimeout(endlessTimeOut);
    }

    if (success == null) {
        success = function(transport){
            document.getElementById('global-content-main').innerHTML = transport.responseText;
            //this.toggleLoad(false);
        };
    }

    if (failure == null) {
        failure = function(transport){
            document.getElementById('global-content-main').innerHTML = transport.responseText;
            //this.toggleLoad(false);
        };
    }

	this.onSuccess = success;
	this.onFailure = failure;
	this.setRequest('/home/'+calling,"get","");

};

controller.prototype.showvid = function(bool){

  var w = site.getBrowserWidth();
  var h = site.getBrowserHeight();

  if (bool)
  {
    document.getElementById("overlay").attributes["class"].nodeValue = "";
    
    site.setRule("#overlay",{duration: 0.8, width: w+"px", height: h+"px", zIndex: 980});
    new Effect.Appear("overlay",{from: 0.0, to: 0.5, afterFinish: function(){
      }});

    document.getElementById("video").attributes["class"].nodeValue = "";
    site.setRule("#video",{
	marginTop: (window.pageYOffset + 200)+'px',
	marginLeft: (site.getBrowserWidth()/2)-275+'px',
	zIndex: 999
      });
  }else{
    new Effect.Fade("overlay",{duration: 0.8, from: 0.5, to: 0.0, afterFinish: function(){
	document.getElementById("overlay").attributes["class"].nodeValue = "irrelevant";
	site.setRule("#overlay",{width: "0px", height: "0px"});
	site.setRule("#overlay",{zIndex: -999});
      }});
    document.getElementById("video").attributes["class"].nodeValue = "irrelevant";
    site.setRule("#video",{zIndex: -999});
  }
  
};

//controller.prototype.showvid = function(bool){

  //var w = site.getBrowserWidth();
  //var h = site.getBrowserHeight();

  //if (bool)
  //{
    //document.getElementById("overlay").attributes["class"].nodeValue = "";
    
    //site.setRule("#overlay",{width: w+"px", height: h+"px", zIndex: 980});
    //site.shiftCss({ selector: '#overlay', inc: 0.05, iter: 20, from: 0.0, to: 0.5, rule: "opacity",afterFinish: function(){
	//console.log("done");
      //}});

    //document.getElementById("video").attributes["class"].nodeValue = "";
    //site.setRule("#video",{
	//top: (window.pageYOffset + 250)+'px',
	//left: site.getBrowserWidth()/2-150+'px',
	//zIndex: 999
      //});
  //}else{
    //site.shiftCss({ selector: '#overlay', inc: 0.05, iter: 20, from: 0.5, to: 0.0, rule: "opacity",afterFinish: function(){
	//console.log("done");
	//document.getElementById("overlay").attributes["class"].nodeValue = "irrelevant";
	//site.setRule("#overlay",{width: "0px", height: "0px"});
	
      //}});
    //document.getElementById("video").attributes["class"].nodeValue = "irrelevant";
    //site.setRule("#video",{zIndex: -999});
    //setTimeout(function(){site.setRule("#overlay",{zIndex: -999});},900);
  //}
  
//};


var site = new controller();
site.create_handler(site);
//setInterval(function(){site.startClock();},1000);

