var Site = Class.create({

    COOKIENAME: "avastin-base",
    _session: null,
    _cookieObject: null,
    _calledFromNav: false,
    _pageLoaded: false,
    
    initialize: function(config) {
      
      if(!this.isThisIe6()  && !this.isThisSearchpage())this._setPageTransition();
      this. _initCookieObject();
      this.id = config.id;
      this._initSwfobject();
      // header nav
      if(!this.isThisIe6() && !this.isThisMobile())this._initHeaderNav();
      this._initDialogController();
      this._initGlossary();
      this._initTextZoom();
      this._initEmail();
      if(!this.isThisIe6() && !this.isThisMobile())this._initPageChangeEvent();
      //initialize copay handler
      this._initCoPay();
      this._initHcpLink(); 
    //  this._initSitemapController();
      this._initOmniture();
    },

    /** @private */
    
    _initCookieObject: function(){
      this._cookieObject = new CookieJar({
          expires: (60*60*24*7),
          path: "/"
        });
    },
    
    _setPageTransition: function(){
      this.transitionContoller = new TansitionController();
    },
    
    _initSitemapController: function(){ 
      this.sitemapController = new SitemapController(0);
    },
    
    _initSwfobject: function() {
      $$("a.swf-item").each(function(item){
          var swf = new SwfobjectLoader(item);
        });
    },
    
    _initDialogController: function(){
      this.dialogController = new DialogController();
    },
    
    _initHcpLink: function(){
      $$(".hcp-link").each(function(el){
        el.observe('click',function(ev){
          ev.stop();
          this.dialogController.onHcpClick.bind(this.dialogController)(ev.findElement('a').href);
        }.bind(this));
      }.bind(this));
    },
    
    _initCoPay: function() { 
      //if there are any elements with id co-pay-check, iterate over them
      //and add a new check system
      $$("#co-pay-check").each(function(item) {
        var coPay = new CoPayCheck(item);
      });
    },
    
    _initHeaderNav: function(){
      var body = $$("body")[0];
      var height = "373px";
      if(body.hasClassName("state1"))height="266px";
      if(body.hasClassName("state2"))height="145px";
      $("nav-shadow").style.height = height;
      var flashvars = {configPath:contextPath+subPath+"/base/patient/media/flash-nav/config.xml",
                       contextPath:contextPath,
                       subPath:subPath,
                       mediaPath: contextPath+"/base/patient/media/flash-nav/"};
      var params = {AllowScriptAccess: "always",wmode:"transparent"};
      var attributes = {}; 
      swfobject.embedSWF(contextPath+subPath+"/base/patient/media/flash-nav/avastin-flash-nav.swf", "flash-header", "928", "373", "9.0.0","", flashvars, params, attributes);
    },
    
    _initOmniture: function(){
      this.omniture = new Omniture();
      if(this.isThisSearchpage() || this.isThisIe6()) window.trackOmniture(location.href);
    },
    
    _initGlossary: function() {
      this.glossary = new Glossary(this);
    },

    _initTextZoom: function() {
      this.textZoom = new TextZoom(this);
    },
    
    _initEmail: function(){
      var emailPage = new EmailPage();
    },
    
    _initPageChangeEvent: function() {

      var oldUrl = "";
      oldUrl = location.href;
      
      if(oldUrl.match("#/")){
        var urls = oldUrl.split("#/");
        if(urls[0].endsWith("/"))urls[0]+="index.html";
        oldUrl = urls[0];
      }
      
      // SWFAddressEvent.CHANGE is called when the URL changes.
      
      SWFAddress.addEventListener(SWFAddressEvent.CHANGE,function(){
        
        if(oldUrl.length==0) return;
        
        var url = SWFAddress.getValue();
        
        // TODO Determine what needs to be updated
        if(!url.startsWith(contextPath)){
          url = (typeof url != 'undefined' && url!="/")? url.substr(1) : location.href;
        };

        if(!url.endsWith(oldUrl)){ 
          this.transitionContoller.navigation.loadPage.bind(this.transitionContoller)(url);
        };
        
      }.bind(this));
      
      
      // document:pageLoaded is fired inside of TransitionController after the transition is completly done.
      
      document.observe("document:pageLoaded",function(){ 
        // rerunning all those js functions that assgin events to elements
        site._refreshJs.bind(this)();

        var status = arguments[0].memo.status;
        var newUrl = arguments[0].memo.url.include(location.host)? arguments[0].memo.url.split(location.host)[1] : arguments[0].memo.url ;

        if(typeof status == "number" && status!=200) newUrl = "errorPage";
        $$('#email-form form')[0].setAttribute('action',newUrl);
        
        // setting perma-link
        $$(".perma-link").each(function(el){
          el.href = newUrl != "errorPage"? "http://"+location.host+newUrl : contextPath;
        });
        
        $("email-this-page-form").pageTitle.value = $$("title")[0].innerHTML;

        oldUrl = newUrl;
        
        // setting the new url to the history
        SWFAddress.setValue(newUrl);
      
        var func = document.getElementById('flash-header').callChangePage;
        
        if(typeof func != "undefined"){
          document.getElementById('flash-header').callChangePage(newUrl);
        };
        new Effect.ScrollTo("container",{ duration:'0.5'});
 
      }.bind(this));
    },
    
    _refreshJs: function(){
      site._pageLoaded = true;
      site.glossary.refresh.bind(site.glossary)();
      site.omniture.initDownload.bind(site.omniture)();
      site._initCoPay.bind(this)();
      site._initHcpLink.bind(site)();
      window.setLinks();
    },
    
    
    getCookie: function() {
      if(!this._session) {
        this._session = this._cookieObject.get(this.COOKIENAME);
      }
      return this._session;
    },
    
    setCookie: function(obj) {
      var output = obj;
      if(this._session) {
        var temp = this._session;
        for(var k in temp) {
          if(output[k] === undefined) {
            output[k] = temp[k];
          }
        }
      }
      this._cookieObject.put(this.COOKIENAME, output);
    },
    
    /* flash interface */
    onFlashNavHcpClick: function(url){
      site.dialogController.onHcpClick.bind(site.dialogController)(url);
    },
    
    changePage: function(url){ 
      if(!this.isThisSearchpage()){
        this._calledFromNav = true;
        this.transitionContoller.navigation.loadPage.bind(this.transitionContoller)(url);
        this.omniture.omniLinkClick(url);
      }else{
        location.href=url;
      }
    },
    
    changeFlashNavSize: function(to,state){ 
      var tg = $("nav-shadow");
      to-=3; // to adjust the percent scaling 
      new Effect.Scale(tg,(to*100)/parseFloat(tg.style.height),{
        scaleX:false,
        transition: Effect.Transitions.ExpoEaseTo,
        duration: .8
      });
      
    },
    
    showDialog: function(msg,cfg){
      site.dialogController.showDialog(msg,cfg);
    },
    
    onFlashLoad: function(){
      if(!(document.getElementById && document.all&&(navigator.appVersion.indexOf("MSIE 6.")>=0))) $$(".no-flash")[0].removeClassName("no-flash");
    },
    
    /* util */

    isThisIe6: function(){
      return document.getElementById && document.all&&(navigator.appVersion.indexOf("MSIE 6.")>=0);
    },
    
    isThisIe7: function(){
      return document.getElementById && document.all && (navigator.appVersion.indexOf("MSIE 7.")>=0);
    },
    
    isThisSearchpage: function(){
      return location.href.match("search");
    },
    
    isThisMobile: function(){
      var agent=navigator.userAgent.toLowerCase();
      return (agent.indexOf('mobile')!=-1);
    }
    
    
  });

