﻿var _contentCache = {};

var DIRECTION_LEFT = 'left';
var DIRECTION_RIGHT = 'right';

var _contentId = '#mainContent';
var _contentIdNotJQuery = 'mainContent';
var _movedOldContentId = '#tempOldContent';
var _movedOldContentTemplate = '<div id="tempOldContent" style="position:fixed"></div>';
var _movedNewContentId = '#tempNewContent';
var _movedNewContentIdNotJQuery = 'tempNewContent';
var _movedNewContentTemplate = '<div id="tempNewContent" style="position:fixed"></div>';
var _ajaxLoaderId = '#ajaxLoader';

var _currentSlideDirection = DIRECTION_LEFT;
var _currentHref = null;
var _currentHash = window.location.hash;

var _isLoading = false;

var _tempLink;
var _tempDirection;
var _tempCache;
function LoadContent(link, direction, ignoreCache, ignoreCurrentPage) {

    var currentLocation = window.location.href.replace('#/', '');

    if (currentLocation == link.href && !ignoreCurrentPage) {
        return;
    }

    if (_isLoading) {
        _tempLink = link;
        _tempDirection = direction;
        _tempCache = ignoreCache;
        setTimeout("LoadContent(_tempLink, _tempDirection, _tempCache)", 2000);
        return false;
    }

    _isLoading = true;

    window.location.hash = GetLinkHash(link);
    _currentHash = window.location.hash;    

    _currentSlideDirection = direction || DIRECTION_LEFT;

    // save current content
    if (!_contentCache[window.location] && !ignoreCache) {
        _contentCache[window.location] = GetCurrentContent();
    }

    // 1.
    var target = link.href;
    _currentHref = target;

    SwitchLoaderImage(true);

    var newContent = null;
    if (!_contentCache[target]) {
        // 2.1
    	$.ajax({
    		url: target,
    		dataType: 'script',
    		success: function (data) {
    			ProcessNewContent(data);
    		}
    	});
    }
    else {
        // 2.2
        newContent = _contentCache[target];
        PerformSlide(newContent);
    }
}

function GetLinkHash(link) {
    var globalPrefix = 'http://' + document.domain;
    var localLink = link.href.substring(globalPrefix.length);
    
    if (localLink == '/default.aspx') {
        localLink = '/';
    }
    return localLink;
}

function SwitchLoaderImage(isShow) {
    if (isShow) {
        $(_ajaxLoaderId).show();
    }
    else {
        $(_ajaxLoaderId).hide();
    }
}

function ProcessNewContent(data) {
	
    var targetDivStart = '<div id="mainContent">';
    var tergetDivEnd = '</div><!-- end mainContent -->';

    // taking everything inside of target div
    var indexStart = data.indexOf(targetDivStart) + targetDivStart.length;
    var indexEnd = data.indexOf(tergetDivEnd);

    var newContent = data.substring(indexStart, indexEnd);
    _contentCache[_currentHref] = newContent;

    PerformSlide(newContent);
}

function PerformSlide(content) {
    var contentBlock = $(_contentId);
    $('.footer').hide();
    // 3.
    // adding temp. block
    contentBlock.parent().append(_movedOldContentTemplate);
    // moving old content there
    contentBlock.clone().appendTo(_movedOldContentId);

    // 4.
    contentBlock.empty();

    // 5.
    contentBlock.parent().append(_movedNewContentTemplate);

    //newContentBlock.html(content);
	// so that <script> won't be removed from content
    document.getElementById(_movedNewContentIdNotJQuery).innerHTML = content;

    var newContentBlock = $(_movedNewContentId);
    var oldContentBlock = $(_movedOldContentId);    

    var logo = $('#logo');
    var icons = $('#icons');
    var px = 'px';
    var top = 'top';
    var opacityName = 'opacity';
    var opacityValue = '0.2';
    newContentBlock.css(top, logo.height() + icons.height() + px);
    oldContentBlock.css(top, logo.height() + icons.height() + px);
    newContentBlock.css(opacityName, opacityValue);
    oldContentBlock.css(opacityName, opacityValue);

    newContentBlock.css('width', contentBlock.css('width'));

    var leftValue = '1000px';
    var contentBlockStartPositionLeftValue = leftValue;
    if (_currentSlideDirection == DIRECTION_LEFT) {
        contentBlockStartPositionLeftValue = '+' + leftValue;
        leftValue = '-=' + leftValue;
    }
    else {
        contentBlockStartPositionLeftValue = '-' + leftValue;
        leftValue = '+=' + leftValue;
    }

    newContentBlock.css('left', contentBlockStartPositionLeftValue);

    // 6.
    SwitchLoaderImage(false);
    var speedMs = 200;
    newContentBlock.animate({ left: leftValue },
                                speedMs,
                                'linear',
                                function () {
                                	// again, so that <script> tag won't be removed
                                	document.getElementById(_contentIdNotJQuery).innerHTML
										= document.getElementById(_movedNewContentIdNotJQuery).innerHTML;

                                	$(_movedNewContentId).remove();

                                	if (_currentHref.indexOf('brief.aspx') >= 0) {
                                		UpdateBoxesAjax();
                                	}
                                });

    oldContentBlock.animate({ left: leftValue },
                                speedMs,
                                'linear',
                                function() {
                                    $(_movedOldContentId).remove();
                                    $('.footer').show();
                                    _isLoading = false;
                                });
}

function GetCurrentContent() {
    return $(_contentId).clone();
}

function LoadPage() {
    var hashIndex = window.location.href.indexOf('#/');
    if (hashIndex > -1) {
        var location = GetValidLocation(); ;
        var defaultPage = 'http://' + document.domain + '/';
        if (location != defaultPage) {
            var pseudoLink = {};
            pseudoLink.href = location;
            LoadContent(pseudoLink, null, true, true);
        }
    }

    // starting back/next poller
    setInterval(function() {
        if (window.location.hash != _currentHash && _isLoading == false) {
            var location = GetValidLocation();
            var pseudoLink = {};
            pseudoLink.href = location;
            LoadContent(pseudoLink, null, null, true);
        }
    }, 200);
}

function GetValidLocation() {
    var location = window.location.href;
    // root
    if (location.indexOf(document.domain + '/#/') > -1) {
        location = location.replace('/#/', '/');
    }
    // any other page
    else {
        var hashIndex = location.indexOf('#/') + 1;
        location = location.substring(hashIndex, location.length);
    }
    return location;
}