// this is the front end brains behind cypher13.com. its pretty dope.
// by Collin Schaafsma @ Quick Left. www.quickleft.com
// for our good friends at cypher13. all for love.

//set some vars so this beast can run
var $wrapper = $('#wrapper'),
currentHash = location.hash,
pageObj = eval('({"dashboard":{"sections":{"news":{"id":"news","expanded":"0","height":"0","canToggle":"1","canPinPoint":"0","isLoaded":"0"}, "sales":{"id":"sales","expanded":"0","height":"0","canToggle":"1","canPinPoint":"1","isLoaded":"0"},"market":{"id":"market","expanded":"0","height":"0","canToggle":"1","canPinPoint":"1","isLoaded":"0"}}}})'),
canFolioLoad = "1",expandedObj = eval('({"expanded":{"client":"0","category":"0","date":"0"}})'),
lastRowHeight = '0',sorterOffset = 0,
viewStyle = 'full';
jQuery(
	function ($) {
		//sorry ie6 users
		if(jQuery.browser.version == '6.0'){window.location = '/ie6-is-old.php';}
		//get the party started right
		init();
		bindEvents();
		function init(){
	   		$body = $('html,body').attr('scrollTop',0);
	   		preLoad();
	   	}
	
	   	function preLoad(){
	   		$wrapper.css({height:0,overflow:'hidden'});
	     	$(window).bind('load',doLoad);
	   	}
	
		function doLoad(e){
			setSectionHeights();
			var i;
			
			processHash(location.hash.slice(1));
			$wrapper.css({height:'auto',overflow:'auto'})
			//hide the pre-loader
			$('#preloader').css({display:'none'});
		}
		
		function bindEvents(){
			$('.toggleSec').bind('click',toggleSectionClick);
			
			$('.section > h2').mouseover(function(){
				$(this).parent().find('.btnOpen').removeClass('btnOpen').addClass('btnOpenOver');
			}).mouseout(function(){
				$(this).parent().find('.btnOpenOver').removeClass('btnOpenOver').addClass('btnOpen');
			});
		}
		
		function toggleSectionClick(e){
			processHash(this.hash.slice(1));
		}
		
		//set heights
		function setSectionHeights(){
			for (_section in pageObj.dashboard.sections) {
				pageObj.dashboard.sections[_section].height = $('div#sec_'+_section+' .sec_content').height()+'px';
			}
		}
		
		//process incoming hash string
		function processHash(locationHash){
			if(locationHash!='') {
				currentHash = locationHash.split(",");
				if(currentHash.length > 1){
					//section identifier
					//move page around
					loadSection(currentHash[0]);
				}else{
					//just a section load
					loadSection(currentHash[0]);	
				}
			}
		}
		
		function loadSection(section){
			var sec = new Section(section).toggle();
		}
		
	}
);

function News(){
	//later news might get some action
	init();
	
	function init(){

	}

	this.load = function(){
		
	}	

}

function Sales(){
	init();
	
	function init(){

	}
	
	this.load = function(){

	}	
}

function Market(){
	init();
	
	function init(){

	}
	
	this.load = function(){

	}	
}

function Section(section){
	var $sec = $('div#sec_'+section),
	$sec_content = $('div#sec_'+section+' .sec_content'),
	$sec_btn = $('div#sec_'+section+' .btnToggle'),
	sec_height = pageObj.dashboard.sections[section].height,
	secObj = null;
	
	init();
	
	function init(){
		canFolioLoad = "0";
	}
	
	this.toggle = function(){
		if(pageObj.dashboard.sections[section].expanded == '1'){
			//section is expanded, so close it
			if(pageObj.dashboard.sections[section].canToggle =='1'){
				close();
			}
		}else{
			var scroller = new Scroller(section,'div#sec_'+section).pinPoint();
			//section is closed so expanded it
			//mark that sec as loaded so we don't do that again
			if(pageObj.dashboard.sections[section].canToggle =='1'){
				open(section);
			} else {
				getSectionObj().load();
			}
		}
	}
	
	function close(){
		$sec_content.animate({opacity:'0'}, {duration:800,queue:'section',scope:'section',preDelay:0});
		$sec_content.animate({height:'0px'}, {speed:800,duration:800,queue:'section',scope:'section',easing:'easeInOutExpo',preDelay:100},null,function(){
			$sec_btn.removeClass('btnClose').addClass('btnOpen');
			canFolioLoad = "1";
		});
		$sec_content.animate({paddingTop:'0px'}, {speed:800,duration:500,queue:'section',scope:'section',easing:'easeInOutExpo',preDelay:100});

		pageObj.dashboard.sections[section].expanded = '0';
		
	}
	
	function open(section){
		var timing = 800;
		
		$sec_content.css({height:"0px",opacity:'0'});
		$sec_content.animate({height:sec_height}, {speed:timing,duration:timing,queue:'section',scope:'section',easing:'easeInOutExpo',preDelay:200},null,openCallBack);
		$sec_content.animate({paddingTop:'5px'}, {speed:timing,duration:timing,queue:'section',scope:'section',easing:'easeInOutExpo',preDelay:200});
		pageObj.dashboard.sections[section].expanded = '1';
	}
	
	function openCallBack(){
		getSectionObj().load();
		$sec_content.animate({opacity:'1'}, {duration:1200,queue:'section',scope:'section',preDelay:0});
		$sec_btn.removeClass('btnOpen').addClass('btnClose');
		canFolioLoad = "1";
	}
	
	function getSectionObj(){
		switch(section){
			case 'news':
				secObj = new News();
				break;
			case 'sales':
				secObj = new Sales();
				break;
			case 'market':
				secObj = new Market();
				break;
			default:	
		}
		return secObj;	
	}
}

function Scroller(section,target){
	var $target = $(target),
	targetOffset = ($target.offset().top - 4),
	headerSize = ($('#header').height()+17);

	
	init();
	
	function init(){
		//stop the auto loader while we move things around
		if(targetOffset > headerSize){
			canFolioLoad = "0";
		}else {
			//we didn't move so we better assign this now
			//location.hash = currentHash;
		}
		
		if(section == 'work'){
			//change offset when when sorter is not engaged
			//console.debug('windowScroll='+$(window).scrollTop()+' - sorterOffset='+sorterOffset);
			
			if(sorterOffset > $(window).scrollTop())
			{
				//console.debug('we do offset');
				targetOffset = (targetOffset - 20);
			} else {
				targetOffset = (targetOffset + 35);
			}
		}
		
	}
	
	this.pinPoint = function(){

		if(pageObj.dashboard.sections[section].canPinPoint == "1"){
			if(section == 'work'){
				scrollDur = 200;
			}else{
				scrollDur = 800;
			}

			$('html,body').animate({scrollTop: targetOffset}, {speed:200,duration:scrollDur,queue:'section',scope:'section',easing:'easeOutExpo',preDelay:0},null,function(){
				canFolioLoad = "1";
			});
			$.fxqueue("section").stop();
		} else {
			//make sure we let it load again on none pinpoint sections.
			canFolioLoad = "1";
		}
	}
}

/**
 * Cookie plugin
 */
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

