// fix 'Flash of Unstyled Content
document.write('\n<style type="text/css">\n');
document.write('.hidedialog { display:none !important }\n');
document.write('.FOUC { display:none !important }\n');
document.write('</style>\n');


dojo.require("dojo.fx");
dojo.require("dojo.hash");
dojo.require("dojo.parser");
dojo.require("dojo.behavior");
dojo.require("dojo.NodeList-traverse");
dojo.require("dojo.fx.easing");
dojo.require("dojo.cache");

dojo.require("dijit.Dialog");

dojo.require("dojox.gfx");
dojo.require("dojox.gfx.fx");


var articleTitle = "";
var pageState = "";
var uri_fragment = '';
var locationState = "";
var appended_title = " - creating content that pays";
var page_refreshed = 1;


window.onunload = function() {
  cleanUp();
  cleanWork();
};

function cleanUp() {
  dojo.unsubscribe("/dojo/hashchange");
  dojo.unsubscribe("/fwd/pageloading");
}


dojo.addOnLoad(function() {
	// add class to remove from screen while is loading  for 1st time
	dojo.query('#navigation').addClass('offscreen'); //Dimtiris	
	
  // google's url fragment
  if( _esc_fragment() ){
    //var _location = window.location.pathname.substring(0, window.location.pathname.lastIndexOf('/')+1);
    //_goto_url(_location+'#!'+pageState);
    dojo.publish("/fwd/pageloading", [pageState]);
    //return;
  } else if (_nonhash_request()) {
	  
	window.location.href = window.location.pathname.substring(0, window.location.pathname.lastIndexOf("/")) + '#!' + window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1,window.location.pathname.lastIndexOf('.'));


  } else {
	pageState = window.location.hash; //window.location.href;

	if(pageState.indexOf('blog') >= 0) { //awkward?!?!
      _goto_url('../blog');
      return;
    }
  }
  
  dojo.query('HTML').removeClass('no-js');
  
  // watch for url changes or page loads
  dojo.subscribe("/dojo/hashchange", null, _get_content);
  dojo.subscribe("/fwd/pageloading", null, _get_content);

  // set page elements for fade in
  if(dojo.isIE) {
    dojo.style('navigation', 'opacity', '0.0');
    dojo.style('content', 'opacity', '0.0');
  }
  else {
    dojo.style('navigation', 'opacity', '0');
    dojo.style('content', 'opacity', '0');
  }

  // remove the hidden content
  dojo.query('#navigation').removeClass('FOUC');
  dojo.query('#content').removeClass('FOUC');
  



  // set off page flip animation and fade in nodes
  if((document.referrer.indexOf('blog') !== (-1)) && (pageState === '#!index') || (pageState === '')) {
 _no_anim_page_start();
  } else {
    _no_anim_page_start();
  }

  var content_area = dojo.byId('content');
  var anim_page = dojo.byId('viewarea');
  
  
  // replace all the links in the navigation with hashbangs.
  dojo.query('#navigation a').forEach(
  	function(item){
		var currHref = dojo.attr(item, 'href')
		if(currHref.indexOf('.php')>0) {
			currHref = currHref.replace('.php','');
			dojo.attr(item, 'href', '#!'+currHref);
		}
		
	}
  );
  
    
  // assign button behaviours
  dojo.behavior.add({
    '#navigation li:not(li.logo) > a' : {
      onclick: function(e) {
        e.preventDefault();

        if(uri_fragment) {return;}

        if(this.href.indexOf('blog') >= 0) {
          _goto_url(e.currentTarget.href);
        } else {
          // update title
          document.title = e.target.textContent + appended_title;
		  var url = _esc_fragment();
		  if(!url){ url = e.currentTarget.hash.replace('#!',''); }
		  dojo.hash('!'+url, true);
          dojo.query('#navigation li').removeClass('selected');
          dojo.query(this.parentNode).addClass('selected');
        }
      }
    },
    '#navigation li.logo a' : {
      onclick: function(e) {
        e.preventDefault();
        document.title = e.target.textContent + appended_title;
        var url = _esc_fragment();
        if(!url){ url = e.currentTarget.hash.replace('#!',''); }
        dojo.hash('!'+url, true);
        dojo.query('#navigation li').removeClass('selected');
      }
    },
    "a[rel*='external']" : {
      onclick: function(e) {
        this.target = "_blank";
      }
    }
  }); // behaviour

  dojo.behavior.apply();

}); // addOnload


/* *********************************************************** */
/* CHECK IF PAGE BEING REQUESTED IS NON-JS (*.PHP)             */
/* *********************************************************** */

function _nonhash_request(){
	var location = window.location.pathname.substring(window.location.pathname.lastIndexOf('/')+1);
	if (location.indexOf('.php')>0) {
		return true;
	} else {
		return false;
	}
}



/* *********************************************************** */
/* CHECK FOR GOOGLE'S ESCAPED FRAGMENT QUERY                   */
/* *********************************************************** */


function _esc_fragment(){
  var uri = window.location.href;
  var query = uri.substring(uri.indexOf("?") + 1, uri.length);
  var queryObject = dojo.queryToObject(query);

  if(queryObject._escaped_fragment_) {
    pageState = '#!'+queryObject._escaped_fragment_;
    uri_fragment = query;
    return true;
   } else {
     //pageState = window.loction.href;
     return false;
   }
  //return queryObject._escaped_fragment_;
}


/* *********************************************************** */
/* GO TO URL                                                   */
/* *********************************************************** */

function _goto_url(url){
  window.location.href = url; // ...go there directly, what else??
}


/* *********************************************************** */
/* GET PAGE FRAGMENT                                           */
/* *********************************************************** */

function _get_content(hash) {
  var min_content_height = 546;

  if(hash === undefined){hash = 'index';}
  if(hash === '' && window.location.hash === '') { // home
    hash = 'index';
  }
  else if(hash.indexOf('#!') !== (-1)) { // some other page

    hash = hash.replace('#!','');
  }
  else if(hash.indexOf('!') !== (-1)) {
    hash = hash.replace('!','');
  }
  else if(hash.indexOf('#') !== (-1)) {
    hash = hash.replace('#','');
  }
  else {
    hash = '404';
  }

  hash +=  "-fragment.php";

  // Load the new page content
  var text = dojo["cache"](new dojo._Url(hash), {sanitize: true});


  // hack to add 0 opacity to content area
  if(dojo.isIE) {
    text = text.replace( 'id="content"', 'id="content" style="zoom:1; opacity:0.0"' );
  } else {
    text = text.replace( 'id="content"', 'id="content" style="opacity:0"' );
  }
  
  
  // comented out because breaks the URL on clients pop-up
  
  // text = text.replace( /a href="/g, 'a href="#!' );
 
  text = text.replace( /#!http/g, 'http' );
  text = text.replace( /.php/g, '' );



  // replace and show new content if page refreshed
  if(page_refreshed){
      _refresh_content();
      page_refreshed = 0;
  }
  else { // fade out old content first
    dojo.fadeOut({
      node: dojo.byId('content'),
      duration: 200,
      onEnd: function(){
        _refresh_content();
      }
    }).play();
  }

  var _height;
  function _refresh_content() {
      dojo.place(text, dojo.byId('content'), 'replace');
      dojo.fadeIn({node: dojo.byId('content')}).play();

      // not sure how to activate these elsewhere, independantly -- activate only once
      if(dojo.query('#content div')[0].className == 'clients') { _activate_clients(); }
      if(dojo.query('#content div')[0].className == 'work') { _activate_work(); }
      if(dojo.query('#content div')[0].className == 'contact') { _load_map(); }
      _height = dojo.marginBox('content').h+120;
      if(_height < min_content_height) {_height = min_content_height;}

      dojo.style(dojo.byId('page'), 'height', _height+"px");
      dojo.style(dojo.byId('viewarea'), 'height', _height+"px");
      dojo.style(dojo.byId('page_edge'), 'height', _height+"px");

      // This fixes the shift that occurs in a centered layout when the page grows and forces scrollbars to appear.
      if(!dojo.isIE < 8){
        if (dojo.body().scrollHeight > dojo.window.getBox().h) {
           dojo.style('page', 'right', '-8px');
        } else {
           dojo.style('page', 'right', '0');
        }
      }
  } // _refresh_content

} // _get_content



/* *********************************************************** */
/* FADE IN A BUNCH OF DOM NODES                                */
/* *********************************************************** */

function _fade_in_nodes(/*array of nodes*/ nodes, /*duration*/ d) {
  if(!nodes || !d) {return;}

  var nodeArr = [];
  dojo.forEach(nodes, function(obj_node) {
    nodeArr.push(
      dojo.fadeIn({
        node: obj_node,
        duration: d
      })
    );
  });
  dojo.fx.combine(nodeArr).play();
}


/* *********************************************************** */
/* PAGE FLIP ANIMATION                                         */
/* *********************************************************** */

function _anime_page_edge() {
  var surface1 = dojox.gfx.createSurface("canvas", 970, 546);
  var single_line, single_line2, page_flip;
  var lineObjs = [], pageObjs = [];
  var _count = 1; var pg = 1;
  for(indx=1; indx<10; indx++){
    page_flip = surface1.createImage({width: 970, height: 546, x: 970, y: 0, src: "assets/home/ani"+indx+".jpg"});
      pageObjs.push(
        dojox.gfx.fx.animateTransform({
          shape: page_flip,
          duration: 250,
          transform: [
            {name: "translate", start: [0, 0], end: [-970, 0]},
            {name: "original"}
          ],
		  easing: dojo.fx.easing.quadIn,
          onEnd: function(){
            dojo.style('page_edge','width', (8*pg++)+"px");
          }
        })
      );
  }

  dojo.style('page_edge','width', "0px");
  dojo.query('#page_edge').removeClass('FOUC');
  var pageAnim = dojo.fx.chain(pageObjs);
  pageAnim.play();

  //Set it so that every time it ends, swap the animated lines with the full static version
  var handle = dojo.connect(pageAnim, "onEnd", function() {

	// hide canvas
	dojo.style('canvas', 'display', 'none');

	// load the content
    dojo.publish("/fwd/pageloading", [pageState]); 

	// fade in the content loaded
	_fade_in_nodes([dojo.byId('navigation'), dojo.byId('content')], 500);
	
	//remove class and space it on creen
	dojo.query('#navigation').removeClass('offscreen'); //Dimtiris
    
	dojo.disconnect(handle);
  });
}

function _no_anim_page_start() {
    dojo.style('canvas', 'display', 'none');
	dojo.style('page_edge', 'height', '546px');
    dojo.publish("/fwd/pageloading", [pageState]);
    _fade_in_nodes([dojo.byId('navigation'), dojo.byId('page_edge'), dojo.byId('content')], 500);
    dojo.query('#page_edge').removeClass('FOUC');
	
	//remove class and space it on creen
	dojo.query('#navigation').removeClass('offscreen'); //Dimtiris	

}


/* *********************************************************** */
/* PAGE EDGE HEIGHT ANIMATION                             */
/* *********************************************************** */

function _animate_height(/*array of nodes*/ nodes, /*duration*/ d, /*height*/ h) {
  if(!nodes || !d || !h) {return;}

  // hide new content, then fade in or animate drop down
  var nodeArr = [];

  // resize left multi-coloured image
  dojo.forEach(nodes, function(obj_node) {
    nodeArr.push(
      dojo.animateProperty({
        node: obj_node,
        duration: d,
        properties: {
          height: { end: h}
          },
        easing: dojo.fx.easing.quadInOut
      })
    );
  });
}


function _is_scrollbar_visible(){
  // Get the computed style of the body element
  var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

  // Check the overflow and overflowY properties for "auto" and "visible" values
  hasVScroll = cStyle.overflow == "visible"
               || cStyle.overflowY == "visible"
               || (hasVScroll && cStyle.overflow == "auto")
               || (hasVScroll && cStyle.overflowY == "auto");
}
