/* --- //

doc: ember.js
site: Wellfire Interactive
development: Cobey Potter, Wellfire Interactive
version: q2, 2009

info: emberEngine front-end framework, v.05. uses jQuery to create front-end framework for site. 
branched for older sites (coded prior to emberEngine)
*/



Ember = function(data){
  
  //set off all the magic
  $("html").addClass('jsActive');
  $("body").attr("oncontextmenu", "return false");
  
  //$.metadata.setType('attr','data-elm');   

  var server = setServer(data.server, ["dev", "stage", "prod"]);

  this.template = new EmberTemplate(data.template);
  this.setTemplate = function(data){ this.template = new EmberTemplate(data); }
  
  this.fx = new EmberFx();
  
  this.form = new EmberForm(data.form);
  this.setForm = function(data){ this.form = new EmberForm(data); }
  
  this.analytics = function(data){
    if(server === "prod" || data.force == 1){
      $.getScript( "http://www.google-analytics.com/ga.js", 
      function(){ 
       try { var pageTracker = _gat._getTracker(data.profile); pageTracker._trackPageview(); } 
       catch(err) { console.log ( "there was an error: " + err);} 
      });
    }
  }
  
  function setServer(serverList, serverStatus){
    if(typeof serverList  == "undefined"){ return serverStatus.pop(); }
    for(var i in serverList){
      if(!serverList[i].match(/http/))
        serverList[i] = "http://" + serverList[i];
      if(serverList[i] == "http://" + window.location.hostname){ return serverStatus.pop(); }
      else{ return serverStatus.shift(); }
    }
  }
  
  this.noHijack = function(){
    // no Hijack :: removes hijacking pages; supplied by Adactio
    if (window.top !== window.self) window.top.location.replace(window.self.location.href);
    /* orig: Faruk Ateş; to be augmented: Wellfire
      if (top !== self && document.referrer.match(/digg\.com\/\w{1,8}/)) {
      top.location.replace(self.location.href);
    }*/
  }
  
}
EmberFx = function(data){
  
  //currently good for now, update for more options: track/no/bounds?, positioning around element
  // does not work in ie6, as ie6 can't create elements outside of body
  this.toolTip = function(bindElm, tip){
    offset = { "x":10, "y":20 };
    delay=600;
    
    $(bindElm).bind("mouseenter", function(e){show(this,e);});
    $(bindElm).bind("mouseleave", function(e){hide(this,e);});
    $(bindElm).bind("mousemove", function(e){move(this,e);});
    
    var show = function(elm, e){
       toolTip = tip.replace(/{tipContent}/, $(elm).attr("title"));
       $(elm).attr("title", "");
       $("html").append(toolTip).children(":last-child").attr("id", "emberTip");
       $("#emberTip")
        .css({
         "position":"absolute", 
         "display":"none",
         "z-index":6000,
         "top": (e.pageY - offset.y) + "px", 
         "left": (e.pageX + offset.x) + "px"
        })
        .fadeIn(delay);
    }
    var hide = function(elm, e){ $(elm).attr("title", $("#emberTip").text()); $("#emberTip").remove(); }
    var move = function(elm, e){ $("#emberTip").css({"top": (e.pageY - offset.y) + "px", "left": (e.pageX + offset.x) + "px"}); }
    
  }
  this.carousel = function(config){
    controls = new Object;
            
    var setup = function() {
      $(config.container).children().css("display", "none");
      $(config.container).children(':first').addClass('viewing').css("display", "block");
      if(config.controls) { setUpControls(); }
      initialize();
    };
    
    var initialize = function(){ controls.timer = setTimeout( function(){ nextImg(config.transitionSpeed) }, config.delay); }
    
    var nextImg = function(dV) {
  		$(config.container).children('.viewing')
  		  .fadeOut(dV)
  		  .appendTo(config.container)
  		  .removeClass('viewing');
    		
  		$(config.container).children(':first')
  		  .fadeIn(dV)
  		  .addClass('viewing');
    		
  		controls.timer = setTimeout( function(){ nextImg(dV) }, config.delay);
  		
  		return;
  	};
    
    var prevImg = function(dV) {
  		$(config.container).children('.viewing')
  		  .fadeOut(dV)
  		  .removeClass('viewing');
    		
  		$(config.container).children(':last')
  		  .prependTo(config.container)
  		  .fadeIn(dV)
  		  .addClass('viewing');
    		
  		controls.timer = setTimeout( function(){ nextImg(dV) }, config.delay);
  		
  		return;
  	};
    
    var setUpControls = function()
      {
        $(config.container).after(config.controls);
        switch($(config.controls).attr("class"))
          {
            default:
            case "overlay":
              controls.overlay();
              $(config.container).siblings('.overlay').children().bind('mouseenter mouseleave', function(){ $(this).toggleClass('on'); } );
              $(config.container).siblings('.overlay').children().bind('click', controls.action );
            break;
          }
      }
    controls.action = function(e){
      clearTimeout(controls.timer);
      if($(e).attr("class") == "prev"){ prevImg(0); } else { nextImg(0); }
      clearTimeout(controls.timer);
      $('html').focus();
      initialize();
      return false;
    }
    controls.overlay = function()
      {
        if(!config.overlay.offOpacity) 
          {
            config.overlay.offOpacity = $(config.container).siblings('.overlay').children().css("opacity"); 
          }
        
        $(config.container).siblings('.overlay').children().fadeTo(0, .05);
        
        $(config.container).siblings('.overlay').bind("click", function(){
          window.location = $('.viewing a').attr('href');
        });
        $(config.container).siblings('.overlay').bind("mouseenter", function(){
            $(config.container).siblings('.overlay').children()
              .animate({opacity: config.overlay.offOpacity}, { duration: 'fast', queue: false});
        });
        $(config.container).siblings('.overlay').bind("mouseleave", function(){
            $(config.container).siblings('.overlay').children()
              .animate({opacity: .05}, { duration: 'fast', queue: false});
        });
      }
    
    
    setup();
    
  }

}
EmberUtil = function(){ 
  this.isLoaded = function(loadElm){ if(!loadElm.complete){ (opts.loadFn)(); isLoaded(loadElm); } return true; }
  this.preloadImg = function(source){ img = new Image(); img.src = source; return img; }
}
EmberTemplate = function(data){
  var fonts = {}; 
  this.template = $(data);
  this.pageType = this.template.attr("class"); //augmented for Patrick Flynn
  
  this.setCufon = function(arrFonts){ 
    for(var i in arrFonts){
      fonts[arrFonts[i].name] = arrFonts[i].src;
    }
  }
  this.cufon = function(font, arrElm){
    $.getScript( fonts[font], 
    function(){ 
      for(var i in arrElm){
        Cufon.replace(arrElm[i]);
      }
      Cufon.now();
    });
  } 
  this.run = function(t, s){ 
    if(this.pageType.match(t)){ 
      switch(typeof s){
        case "function": s.call(); break;
        case "string": 
          if(s.search(/\.js$/i) != -1){ $.getScript(s); }
          else if(s.search(/htm$|\.html$/i) != -1){ /*html -- figure out what you want to do with it later*/ }
        break;
      }
    }
  }
}
EmberForm = function(data){
  if(typeof data  == "undefined"){ return false; }
  else {
    form = new Object();
    form.startEdit = 0, form.formValid = 0;
    form.elm = data.elm;
    form.reqClass = data.reqClass;
    form.requireAll = data.requireAll;
    form.warningMessage = data.warningMessage;
    form.warningClass = data.warningClass;
  }
  
  getReq = function(elm){
    form.reqElm = $(elm).not(":submit").not(":reset").length;
    $(elm).not(":submit").not(":reset").each(function(){
    	if (this.value == $(this).attr('rel') || this.value == form.warningMessage) { form.formValid++; }
    });
  }
  
  setBlur = function(elm){
    elm.blur(function(){
      $(this).removeClass('on');
			if(this.value == '') {
			  if($(this).attr('rel')) this.value = $(this).attr('rel');
  			else this.value = form.warningMessage;
  			$(this).addClass(form.warningClass);
  			if( form.formValid < form.reqElm ) form.formValid++;
  		}else if(this.value != $(this).attr('rel') || this.value != form.warningMessage) { 
  		  $(this).removeClass(form.warningClass);
  		}
  		console.log(form.formValid);
		});
  }
  
  setFocus =  function(elm){
    elm.focus(function(){
      form.startEdit = 1;
      $(this).addClass('on');
			if (this.value == $(this).attr('rel') || this.value == form.warningMessage) { 
	      this.value = ''; 
		    if( form.formValid != 0) form.formValid--;
			};
  	});
  }
  
  if(!form.reqClass){
    form.reqClass = false;
    if(form.requireAll) // check to see if whole form is required.
      getReq(form.elm + ' :input');
  }else{
    form.reqClass = ' .' + form.reqClass;
    getReq(form.elm + form.reqClass);
  }
  
  return {
    validate: function(){
      if(form.reqClass){
        if($(form.elm).find(':input').is(form.reqClass)){
          $(form.elm + " " + form.reqClass).each(function(){        
            setBlur( $(this) );
            setFocus( $(this) );
          })
        }else{ console.log("You do not have any elments with class: " + form.reqClass); }
      }else{
        $(form.elm + ' :input').not(':submit').not(':reset').each(function(){
          setBlur( $(this) );
          setFocus( $(this) );
        });
      }
      $(form.elm + ' :submit').click(function(){
    		if( form.formValid != 0 || form.startEdit == 0 ) {
    			alert("Please fill out the required information.");
    		  return false;
    		}
    	});
    	$(form.elm + ' :reset').focus(function(){ 
    	  form.formValid = form.startEdit = 0; 
    	  return false;
    	});
    }    
  }
}

