var mmh = null;
var fx = null;
var activeElement = null;
var pageWidth = 795;
var currPageId = 0;
var allowSwitchingToPage = true;

var pages = [
    ['index.html', 'pg-home', true],
    ['about-screen-capture-software.html', 'pg-about', false],
    ['whos-it-for.html', 'pg-target', false],
    ['screen-capture-features.html', 'pg-features', false],
    ['screenshots.html', 'pg-screenshots', false],
    ['try.html', 'pg-try', false],
    ['buy.html', 'pg-buy', false]
];

var slideshowTimer = null;
function doSlideshow(objid, start, time)
{
	if(!$chk(objid)){ return; }
	
	if(start){
		clearTimeout(slideshowTimer);
		slideshowTimer = null;
	}
	
	var currObj = null;
	var nextObj = null;
	var firstObj = null;
	
	var i = 0;
	var prevHad = false;
	
	$each($$('#' + objid + ' LI'), function(el){
		if(!i){ firstObj = el; }
		if(nextObj != null){ return; }
		if(prevHad){
			nextObj = el;
		}
		if(el.hasClass('visible')){
			prevHad = true;
			currObj = el;
		}
		i++;
	});

	if(!prevHad || !$chk(nextObj)){
		nextObj = firstObj;
	}
	
	nextObj.addClass('visible');
	nextObj.setStyle('opacity', 0);
	nextObj.setStyle('display', 'block');

	var fx = new Fx.Morph(currObj, {duration: 1000});
    fx.start({ 'opacity': [1, 0] }).addEvent('complete', function(e){
        currObj.removeClass('visible');
    });
    
	var fx1 = new Fx.Morph(nextObj, {duration: 1000});
    fx1.start({ 'opacity': [0, 1] });
    
	slideshowTimer = setTimeout('doSlideshow("' + objid + '", false, ' + time + ');', time);
}

window.addEvent('domready', function(){
	$each($$('A.popup'), function(el){
		el.addEvent('click', function(e){
			e.stop();
			window.open(el.href, 'popup', 'width=400,height=500,toolbar=no,menubar=no,scrollbars=yes');
		});
	});
	
    mmh = $('mm-highlighter');
    fx = new Fx.Morph(mmh, {duration: 400, transition: Fx.Transitions.Sine.easeInOut});
    fx1 = new Fx.Morph(mmh, {duration: 400, transition: Fx.Transitions.Sine.easeInOut});

    //  Set current page
    for(var i = 0; i < pages.length; i++){
        if(pages[i][0] == currentPage || (pages[i][0] == 'index.html' && currentPage == 'home.html')){
            currPageId = i;
            $each($$('#main-menu LI A'), function(el){
                if(el.rel == pages[i][1]){
                    el.parentNode.className = "current";
                    activeElement = el.parentNode;
                    moveToPage(pages[i][1]);
                    performPageStartupActions(pages[i][1]);
                }
            });
            break;
        }
    }

    //  Init element
    highlightActiveElement();

    //  Display content area
    displayContent();

    $('pn-prev').addEvent('click', function(e){
        e.stop();
        movePrevNext(-1);
    });
    $('pn-next').addEvent('click', function(e){
        e.stop();
        movePrevNext(1);
    });

    $each($$('#main-menu LI'), function(el){
        el.addEvent('mouseenter', function(e){
            e.stop();
            var position = this.getCoordinates();
            fx1.cancel();
            fx.start({
                'width': [mmh.getStyle('width'), this.getStyle('width')],
                'left': [mmh.getStyle('left'), position['left']]
            });
        });
        el.addEvent('click', function(e){
             e.stop();
             
             if(!allowSwitchingToPage){ return false; }
             
             if($chk(activeElement)){
	             activeElement.removeClass('current');
             }
             
             activeElement = this;
             
             this.addClass('current');
             highlightActiveElement();

             if($chk(this.childNodes)){
                for(var i = 0; i < this.childNodes.length; i++){
                    if($chk(this.childNodes[i].rel) && this.childNodes[i].rel != ''){
                        moveToPage(this.childNodes[i].rel);
                    }
                }
             }
        });
        el.addEvent('mouseleave', function(e){
             e.stop();
             if(!activeElement){
                return;
             }
             var position = activeElement.getCoordinates();
             fx.pause();
             fx1.start({
                 'width': [mmh.getStyle('width'), activeElement.getStyle('width')],
                 'left': [mmh.getStyle('left'), position['left']]
             });
        });
    });
}); //  domready

function pageExists(pageid)
{
    for(var i = 0; i < pages.length; i++){
        if(pages[i][1] == pageid){
            return i;
        }
    }

    return -1;
}  //  pageExists

function movePrevNext(factor)
{
    currPageId += factor;
    if(currPageId < 0){
        currPageId = pages.length - 1;
    }
    if(currPageId >= pages.length){
        currPageId = 0;
    }

    moveToPage(pages[currPageId][1]);

    $each($$('#main-menu LI A'), function(el){
        if(el.rel == pages[currPageId][1]){
            el.parentNode.addClass("current");
            if($chk(activeElement)){
                activeElement.removeClass("current");
            }
            activeElement = el.parentNode;
            highlightActiveElement();
        }
    });
}  //  movePrevNext

function moveToPage(pageid)
{
    var pageIdx = pageExists(pageid);
    if(pageIdx < 0 || pageIdx > (pages.length - 1)){
        return;
    }

    currPageId = pageIdx;
    var leftPos = pageWidth * pageIdx * (-1);
    obj = $('pages');

    var fx = new Fx.Morph(obj, {duration: 1000, transition: Fx.Transitions.Sine.easeOut});
    fx.start({
        'left': [obj.getStyle('left'), leftPos]
    }).addEvent('complete', function(e){
        loadPageContent(pageid);
        $('pg-generic').innerHTML = '';
    });
}  //  moveToPage

var req = null;

function loadPageContent(pageid)
{
	var pageIdx = pageExists(pageid);
    if(pageIdx < 0 || pageIdx > (pages.length - 1)){
        return;
    }
    
    if(disableAjaxLinks){
    	window.location.href = pages[pageIdx][0];
    	return;
    }
    
    if(!$(pageid) || $(pageid).innerHTML != ''){
        return;
    }
    

    var obj = $(pageid);

    if(req != null){
    	req.cancel();
    	req = null;
    }
    obj.addClass('loading');
    req = new Request.HTML({evalScripts: false});
	allowSwitchingToPage = false;    
    req.get(pages[pageIdx][0] + '?clean=1').addEvent('onComplete', function(responseTree, responseElements, responseHTML, responseJavaScript){
        obj.removeClass('loading');
        if(!this.isSuccess()){
            obj.addClass('loading-error');
            obj.innerHTML = "<strong>Content Loading Problem</strong><br/>Failed to load content from server. We apologize for temporary server issues. <a href='javascript:tryAgain(\"" + pageid + "\")'>Try Again?</a>";
        } else {
            obj.setStyle('opacity', 0);
            obj.innerHTML = responseHTML;
            obj.tween('opacity', [0, 1]);
            performPageStartupActions(pages[pageIdx][1]);
            smoothSwitchUpdate();
            allowSwitchingToPage = true;
        }
    });
}  //  loadPageContent

function tryAgain(pageid)
{
    $(pageid).innerHTML = '';
    loadPageContent(pageid);
}  //  tryAgain

function highlightActiveElement()
{
    var activeElementHighlighted = false;
    $each($$('#main-menu LI.current'), function(el){
        if(activeElementHighlighted){
            return;
        }
        activeElementHighlighted = true;
        var position = el.getCoordinates();
        if(mmh.getStyle('display') != 'block'){
            mmh.setStyle('width', '20px');
            mmh.setStyle('opacity', 0);
            mmh.setStyle('left', (parseInt(position['left']) + 100) + "px");
            mmh.setStyle('display', 'block');
            mmh.setStyle('width', el.getStyle('width'));
            mmh.tween('opacity', [0, 1]);
        }
        fx.start({
            'width': [mmh.getStyle('width'), el.getStyle('width')],
            'left': [mmh.getStyle('left'), position['left']]
        });
        activeElement = el;
    });
}  //  highlightActiveElement

function smoothSwitchUpdate()
{
    $each($$('A.smooth-switch'), function(el){
        if(el.rel != 'alreadyUpdated'){
            el.addEvent('click', function(e){
                e.stop();

                var pageUrl = el.href.split("/");
                pageUrl = pageUrl[pageUrl.length - 1];

                for(var i = 0; i < pages.length; i++){
                    if(pages[i][0] == pageUrl){
                        $each($$('#main-menu LI A'), function(el){
                            if(el.rel == pages[i][1]){
                                el.parentNode.addClass("current");
                                if($chk(activeElement)){
                                    activeElement.removeClass("current");
                                }
                                activeElement = el.parentNode;
                                highlightActiveElement();
                            }
                        });
                        moveToPage(pages[i][1]);
                        break;
                    }
                }
            });
        }
        el.rel = 'alreadyUpdated';
    });
}  //  smoothSwitchUpdate

function displayContent()
{
    $('content-area').set('opacity', 1);
    smoothSwitchUpdate();
    
    $('content-area').setStyle('opacity', 0);
    $('cap').setStyle('height', 100);
    $each($$('.pagenav'), function(el){ el.setStyle('display', 'none'); });
    $('pages').setStyle('opacity', 0);

    var fx = new Fx.Morph($('content-area'), {duration: 400, transition: Fx.Transitions.Sine.easeOut});
    fx.start({'opacity': [0, 1]}).addEvent('complete', function(){
        var fx1 = new Fx.Morph($('cap'), {duration: 1100, transition: Fx.Transitions.Elastic.easeOut});
        fx1.start({'height': [100, 490]}).addEvent('complete', function(){
            $each($$('.pagenav'), function(el){ el.setStyle('display', 'block'); });
            $('pages').tween('opacity', [0, 1]);
        });
    });

}

function getWindowSize()
{
    var Width = 0, Height = 0;
    if(typeof( window.innerWidth ) == 'number'){
        //  non IE browsers
        Width = window.innerWidth;
        Height = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) {
        //IE 6+ in 'standards compliant mode'
        Width = document.documentElement.clientWidth;
        Height = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        Width = document.body.clientWidth;
        Height = document.body.clientHeight;
    }
    return [Width, Height];
}

function setupHome()
{
    window.addEvent('domready', function(){
        $('testimonials').addEvent('click', function(e){
            e.stop();
            showFader(function(){
                //  Fader displayed, display baloon and testimonials
                var position = $('testimonials').getCoordinates();
                var baloon = $('baloon');
                if($chk(baloon)){
                    if(!Browser.Engine.trident4){
                        baloon.setStyle('opacity', 0);
                    }
                    baloon.setStyle('left', parseInt(position['left']) + 57);
                    baloon.setStyle('top', parseInt(position['top']) - 205);
                    baloon.setStyle('display', 'block');

                    if(!Browser.Engine.trident4){
                        var fx = new Fx.Morph(baloon, {duration: 500});
                        fx.start({'opacity': [0, 1]}).addEvent('complete', function(){
                            var baloon_content = $('baloon-content');
                            if($chk(baloon_content)){
                                baloon_content.setStyle('left', baloon.getStyle('left'));
                                baloon_content.setStyle('top', baloon.getStyle('top'));
                                baloon_content.setStyle('display', 'block');
                            }
                            loadTestimonials();
                        });
                     } else {
                        var baloon_content = $('baloon-content');
                        if($chk(baloon_content)){
                            baloon_content.setStyle('left', baloon.getStyle('left'));
                            baloon_content.setStyle('top', baloon.getStyle('top'));
                            baloon_content.setStyle('display', 'block');
                        }
                        loadTestimonials();
                     }
                }
            },
            function(){
                $('baloon-content').setStyle('display', 'none');
                $('baloon').setStyle('display', 'none');
            });
        });
    });
}  //  setupHome

function loadTestimonialById(id)
{
    var obj = $('baloon-text');
    if(!$chk(obj)){
        return;
    }

    var fx = new Fx.Morph(obj, {duration: 400});
    fx.start({'opacity': [1, 0]}).addEvent('complete', function(){
        obj.addClass('loading');
        obj.innerHTML = '';
        obj.setStyle('opacity', 1);

        var req = new Request.HTML();
        req.get('testimonials.php?id=' + id).addEvent('onComplete', function(responseTree, responseElements, responseHTML, responseJavaScript){
            obj.removeClass('loading');
            if(!this.isSuccess()){
                obj.innerHTML = "<strong>Content Loading Problem</strong><br/>Failed to load content from server. We apologize for temporary server issues.";
            } else {
                var res = responseHTML.split("|");
                obj.innerHTML = "<strong>" + res[1] + "</strong><br/>" + res[2];

                $('bcnav-right').rel = res[0];
                $('bcnav-left').rel = parseInt(res[0]) - 2;
            }
        });
    });
}  //  loadTestimonialById

function loadTestimonials()
{
    $('bcnav-left').addEvent('click', function(e){
        e.stop();
        loadTestimonialById(this.rel);
    });
    $('bcnav-right').addEvent('click', function(e){
        e.stop();
        loadTestimonialById(this.rel);
    });
    loadTestimonialById('');
}  //  loadTestimonials

function showFader(onAfterDisplay, onClick)
{
    var windowSize = getWindowSize();

    //  Display fader
    var fader = $('fader');
    if($chk(fader)){
        fader.setStyle('opacity', 0);
        fader.setStyle('left', 0);
        fader.setStyle('top', 0);
        fader.setStyle('width', windowSize[0]);
        fader.setStyle('height', windowSize[1]);

        var fx = new Fx.Morph($('fader'), {duration: 500});
        fx.start({'opacity': [0, 0.7]}).addEvent('complete', function(){
            if(onAfterDisplay){ onAfterDisplay(); }
        });
        fader.addEvent('click', function(e){
            if(onClick){ onClick(); }
            var fx = new Fx.Morph($('fader'), {duration: 500});
            fx.start({'opacity': [0.7, 0]}).addEvent('complete', function(){
                fader.setStyle('width', 1);
                fader.setStyle('height', 1);
                fader.setStyle('left', -100);
                fader.setStyle('top', -100);
                fader.removeEvents();
            });
        })
    }
}  //  showFader

function setupFeatures()
{
	var tooltip = $('tooltip');	
	window.addEvent('domready', function(){
		var fxF = null;
		$each($$('#features-list LI'), function(el){
			el.addEvent('mouseenter', function(e){
				e.stop();
				if(el.className == '1'){ return; }
				$('tooltip').setStyle('display', 'none');
				var position = el.getCoordinates();
				if(el.childNodes.length > 0){
					for(i = 0; i < el.childNodes.length; i++){
						if(el.childNodes[i].tagName == 'P'){
							tooltip.setStyle('opacity', '0');
							tooltip.setStyle('display', 'block');
							tooltip.setStyle('left', parseInt(position['left']));
							tooltip.setStyle('top', parseInt(position['top']) - 80);
							tooltip.className = '1';
							tooltip.innerHTML = el.childNodes[i].innerHTML;

							if(fxF != null){ fxF.cancel(); }
							fxF = new Fx.Morph(tooltip, {duration: 300, transition: Fx.Transitions.Sine.easeOut});
                            fxF.start({
                                'opacity': [0, 0.95],
                                'top': [(parseInt(position['top']) - 150), tooltip.getStyle('top')]
                            });
						}
					}
				}
			});
			el.addEvent('mouseleave', function(e){
				e.stop();
				tooltip.className = '';
				$('tooltip').setStyle('display', 'none');
			});
		});
	});
}	// setupFeatures

function setupTargets()
{
    window.addEvent('domready', function(){
        var tooltip = $('tooltip');
        var fxT = null;
        $each($$('#targets LI A'), function(el){
            el.addEvent('mouseenter', function(e){
                e.stop();
                $('tooltip').setStyle('display', 'none');
                var position = el.getCoordinates();
                if(el.parentNode.childNodes.length > 0){
                    for(i = 0; i < el.parentNode.childNodes.length; i++){
                        if(el.parentNode.childNodes[i].tagName == 'P'){
                            tooltip.setStyle('opacity', '0');
                            tooltip.setStyle('display', 'block');
                            tooltip.setStyle('left', parseInt(position['left']));

                            tooltip.innerHTML = el.parentNode.childNodes[i].innerHTML;
                            tooltip.setStyle('top', parseInt(position['top']) - parseInt(tooltip.getStyle('height')) - 120);
                            tooltip.className = '1';
                            
							if(fxT != null){ fxT.cancel(); }
							fxT = new Fx.Morph(tooltip, {duration: 300, transition: Fx.Transitions.Sine.easeOut});
                            fxT.start({
                                'opacity': [0, 0.95],
                                'top': [tooltip.getStyle('top'), parseInt(tooltip.getStyle('top')) + 50]
                            });
                            
                            break;
                        }
                    }
                }
            });
            el.addEvent('mouseleave', function(e){
                e.stop();
                $('tooltip').setStyle('display', 'none');
                tooltip.className = '';
            });
        });
    });
}  //  setupTargets

function performPageStartupActions(pageid)
{
    if(pageid == 'pg-home'){
        setupHome();
    } else if(pageid == 'pg-target'){
        setupTargets();
    } else if(pageid == 'pg-features'){
    	setupFeatures();
    } else if(pageid == 'pg-about'){
		/*setTimeout('doSlideshow("screenshots", true, 5000);', 5000);*/    	
    } else if(pageid == 'pg-screenshots'){
		milkbox = new Milkbox({ resizeTransition:'back:out', topPosition:30 });
    }
}  //  performPageStartupActions