var mainParam, section, navHeight, currSection;
var minHeight = "30px";
var midHeight = "60px";
var maxHeight = "153px";
var minNav = new Array("home", "blog", "contact");
var midNav = new Array("about");
var maxNav = new Array("work", "case_studies", "gallery");
var drawerClosed = 0;

$(document).ready(function() {

	// case study menu slide
	
	$('#navNode_1').jcarousel({
        animation: 1000,
		auto: 0,
		easing: 'easeInOutCubic',
		initCallback: nav_initCallback,
		scroll: 1,
		wrap: 'both',
        itemVisibleOutCallback: {
			onAfterAnimation : processCtrlBtn
        }
	});
	
	$('#newsScroller').jcarousel({
        animation: 1000,
		auto: 8,
		easing: 'easeInOutCubic',
		scroll: 1,
		wrap: 'both'
	});
	
});

// call back for case study menu

function nav_initCallback(carousel, state) {
	$('.navCtrl').bind('click', function() {
		carousel.next();
	    return false;
	});
};

// update case study menu button

function processCtrlBtn(carousel, item, idx, state) {
	switch ($('.navCtrl').attr('src')) {
		case 'images/global/btn_navMore_up.png':
			$('.navCtrl').attr('src', 'images/global/btn_navBack_up.png');
			$('.navCtrl').attr('alt', 'Back');
			break;
		case 'images/global/btn_navBack_up.png':
			$('.navCtrl').attr('src', 'images/global/btn_navMore_up.png');
			$('.navCtrl').attr('alt', 'More');
			break;	
	}
}

// ------------------------------------------------------------
//
// Get random number from range
//
// ------------------------------------------------------------

function randomFromRange(minVal, maxVal, floatVal) {
    var randVal = minVal + (Math.random() * (maxVal - minVal));
    return typeof floatVal == 'undefined' ? Math.round(randVal) : randVal.toFixed(floatVal);
}

// ------------------------------------------------------------
//
// Format window title
//
// ------------------------------------------------------------

function toTitleCase(str) {
    return str.substr(0,1).toUpperCase() + str.substr(1).toLowerCase();
}      

function formatTitle(title) {
    return 'Pryor Design Company | Ann Arbor, MI' + (title != '/' ? ' | ' + toTitleCase(title.substr(1, title.length - 2).replace(/\//g, ' | ')) : '' );
}

// ------------------------------------------------------------
//
// Custom SWFAddress and Ajax handling
//
// ------------------------------------------------------------

function getTransport() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
}

// ------------------------------------------------------------
//
// Content appear
//
// ------------------------------------------------------------

function appear(content, value) {
    if (typeof value == 'undefined') value = 0;
    var property = content.filters ? 'filter' : 'opacity';
    if (value == 100) {
        if (content.style.removeAttribute) {
            content.style.removeAttribute(property);
        } else {
            content.style[property] = 1;
        }
    } else {
        content.style[property] = content.filters ? 'alpha(opacity=' + value + ')' : value/100;
        setTimeout(function () {appear(content, value + 20)}, 50);
    }
}

// ------------------------------------------------------------
//
// Update content
//
// ------------------------------------------------------------

function updateChange(xhr, svcPath) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            var content = document.getElementById('content');
            content.innerHTML = xhr.responseText;
            appear(content);
			processLiveActions(svcPath);
        } else {
            alert('Error: ' + xhr.status + '!');
        }
    }
}

// ------------------------------------------------------------
//
// Process content
//
// ------------------------------------------------------------

function handleChange(event) {
    var index, rel, links = document.getElementsByTagName('a'), path = event.path;
    if (path.substr(path.length - 1) != '/') {
        path += '/';
    }

    (path == '/') ? event.path = '/home/' : event.path = event.path;

    var pathIdx = event.path.indexOf('/', 1);
    var path_arr = event.path.split('/');
    var docSVCPath = '/' + path_arr[path_arr.length-2] + '/';
    var parameters = '';
    
    for (var p in event.parameters) {
        parameters += '&' + p + '=' + event.parameters[p];
    }

    if (parameters != '') {
        var param_arr = parameters.split('&');
        mainParam = param_arr[1].substring(3, param_arr[1].length);
    } else {
        $('ul#mainNav li div dl').children().each(function() {
            $(this).find('a').removeClass('selected');
        });
    }
	
    var xhr = getTransport();
    xhr.onreadystatechange = function() {
        var svcPath = path;
        updateChange(xhr, svcPath);
    }

    xhr.open('get', 'datasource.php?swfaddress=' + docSVCPath + parameters, true);
    xhr.send('');
    // SWFAddress.setTitle(formatTitle(event.path));

};

function copyLink() {
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData('Text', SWFAddress.getBaseURL() + SWFAddress.getValue());
    } else {
        alert('Unsupported browser.');
    }
}

// ------------------------------------------------------------
//
// Process all behaviors after swfaddress success
//
// ------------------------------------------------------------

function processLiveActions(svcPath, mainNavPath) {
	var svcStr = svcPath.replace(/\//g, "");

	//////////////////////
	//  Global          //
	//////////////////////
	
	// drawer control button
	
	if (svcStr in objCheck(midNav) || svcStr in objCheck(maxNav)) {
		$('#drawerBtn').fadeIn(600);
	} else {
		$('#drawerBtn').fadeOut(600);
	}
	
	// swap images
	
	$.swapImage(".swapImage");
	
	// process navigation height and animate
	
	if (svcStr in objCheck(minNav)) { 
		navHeight = minHeight; 
	} 
	else if (svcStr in objCheck(midNav)) { 
		navHeight = midHeight;
		section = "about_sec";
		
	} 
	else if (svcStr in objCheck(maxNav)) { 
		navHeight = maxHeight;
		section = "work_sec";
	} 
	else { 
		navHeight = minHeight; 
	};
	/*
	$('#drawerBtn').toggle(function() {
		drawerClosed = 1;
		$('#nav').animate({ height: minHeight });
	}, function() {
		drawerClosed = 0;
		$('#nav').animate({ height: navHeight });
	});
	*/
	if (drawerClosed == 0) {
		$('#nav').css('min-height', minHeight);
	    $('#nav').animate({ height: navHeight });
	}

	// process navigation display
	
	if (section) {
		$('#nav .sec').each(function() {
            var sectionId = $(this).attr('id');
            (sectionId == section) ? $(this).css("display", "block") : $(this).css("display", "none");
			// (sectionId == section) ? $(this).delay(300).fadeIn(300) : $(this).fadeOut(300);
        });
	};
	
	// process active nav button
	
	if (svcStr == "case_studies" || svcStr == "gallery" || svcStr == "work") {
		currSection = "work";
	} else {
		currSection = svcStr;
	};
	
	$('ul#mainNav').children('li').each(function() {
        var itemId = $(this).attr('id');
        var navLink = $(this).find('a:eq(0)');
        (itemId == currSection) ? navLink.addClass('selected') : navLink.removeClass('selected');
    });

	// process active category button
	
	if (svcStr == "about") {
		if (!mainParam) {
			mainParam = "team";
		}
		$('#about_sec div').each(function() {
	        var itemId = $(this).attr('id');
	        var navLink = $(this).find('a');
			var key = mainParam + "_sec";
	        (itemId == key) ? navLink.addClass('selected') : navLink.removeClass('selected');
	    });
	} else {
	    $('ul#mainNav li ul').children().each(function() {
	        var itemId = $(this).attr('id');
	        var navLink = $(this).find('a:eq(0)');
	        (itemId == mainParam) ? navLink.addClass('selected') : navLink.removeClass('selected');
	    });
	}
	
	//////////////////////
	//  Home            //
	//////////////////////
	
	// home page gallery
	
	$('#homeGallery').livequery(function(){
        $(this).children('li').each(function() {
            var img01 = $(this).find('.images img').attr('src');
            var img02 = $(this).find('.images img').attr('alt');
            $(this).find('.images').crossSlide({
                sleep: randomFromRange(6, 12),
                fade: .45
            }, [
                {src: img01},
                {src: img02}
               ]
            );
        });
    });

    $('#homeMsging').livequery(function() {
        if ( (navigator.userAgent.match(/iPhone/i)) 
        ||   (navigator.userAgent.match(/iPod/i))
        ||   (navigator.userAgent.match(/iPad/i)) ) { 
            
			$(this).children('li').each(function() {
	            var dtl_img = $(this).find('div.detail img');
	            dtl_img.hide();
	        });
			
        } else {
	
			$(this).children('li').each(function() {
	            var dtl_img = $(this).find('div.detail img');
	            dtl_img.hide();
	            $(this).find('.detail').hover(function() {
	                dtl_img.fadeIn(300);
	            },  function() {
	                dtl_img.fadeOut(300);
	            });
	        });
		}	
		
    });
	
	////////////////////
	//  Work          //
	////////////////////
	
	// case study carousel
	
	var carouselClicked = false;
	var activeBtnNumber = 0;
	
	$('#cSlides').jcarousel({
        animation: 700,
		auto: 5,
		easing: 'easeInOutCubic',
		initCallback: cs_initCallback,
		itemVisibleOutCallback: {
			onAfterAnimation: processNavBtn
        },
		scroll: 1,
		wrap: 'last'
	});
	
	function cs_initCallback(carousel, state) {
		$('#slideNav a').bind('click', function() {
			var targetPnl = $(this).attr('rel');
			var activeBtn = parseInt(targetPnl)-1;
			carouselClicked = true;
			carousel.startAuto(0); 
			activateNavBtn(carousel, activeBtn);
			carousel.scroll($.jcarousel.intval(targetPnl));
			return false;
		});
		carousel.clip.hover(function() {
	        carousel.stopAuto();
	    }, function() {
	        carousel.startAuto();
	    });
		initNavBtn();
	};
	
	function processNavBtn(carousel, item, idx, state) {
		var currItem = idx;
		if (currItem == carousel.size()) {
			currItem = 0;
		} else {
			currItem = idx;
		}
		if (carouselClicked == false) {
			if (activeBtnNumber == carousel.size()) {
				activeBtnNumber = 0;
			}
			activeBtnNumber++;
			activateNavBtn(carousel, activeBtnNumber);
		}	
	};
	
	function initNavBtn() {
		var item = $('#slideNav').find('li:eq(0)');
		var appImg =  item.find('img');
		appImg.attr('src', '/images/work/btn_slideNav_down.png');
	};

	function activateNavBtn(carousel, id) {
		var currItem = id;
		if (currItem == carousel.size()) {
			currItem = 0;
		} else {
			currItem = id;
		}
		$('#slideNav').children('li').each(function() {
			var appImg =  $(this);
			var item_id = appImg.attr('id');
			if (item_id == "slideNav_" + parseInt(currItem)) {
				appImg.find('img').attr('src', '/images/work/btn_slideNav_down.png');
			} else {
				appImg.find('img').attr('src', '/images/work/btn_slideNav_up.png');
			}
		});
	};
	
	// Hover .viewport elements
	
	if ( (navigator.userAgent.match(/iPhone/i)) 
    ||   (navigator.userAgent.match(/iPod/i))
    ||   (navigator.userAgent.match(/iPad/i)) ) {
		
		// do stuff after i get an ipad and can mess around
		
	} else {
		
		$('.viewport').hover(function(e) {
		        $(this).children('a').children('span').fadeIn(200);
		    }).mouseleave(function(e) {
		        $(this).children('a').children('span').fadeOut(200);
		});
		
	}
	
	
	// video player for motion work
	
	var vidPath = "http://beta.prydesign.com/images/work/";
	var vidId = $('#vidContent').attr('class');
	
	if ( (navigator.userAgent.match(/iPhone/i)) 
    ||   (navigator.userAgent.match(/iPod/i))
    ||   (navigator.userAgent.match(/iPad/i)) ) {
		var embedM4V = "<video width='720' height='405' poster='" + vidPath + vidId + ".jpg" + "' controls>" +
	                   "<source src='" + vidPath + vidId + ".m4v" + "' type='video/mp4'>" +
	                   "</video>";
		$('#vidContent').append(embedM4V);
	} else {	
		var flashvars = {};
		var params = {};
		var attributes = {};
		swfobject.embedSWF(vidPath + vidId + ".swf", "vidContent", "720", "444", "9.0.0", "expressInstall.swf", flashvars, params, attributes);
	}
	
	/////////////////////
	//  About          //
	/////////////////////
	 
	var activeId = 'profile_01';
	
	$('ul.bio li').each(function() {
		if ($(this).attr('class') != 'profile_01') {
			$(this).hide();
		}
	});
	
	$('ul.preview').find('li:eq(0)').addClass('active');
	
	$('ul.preview li').click(function() {
		activeId = $(this).find('a').attr('class');
		
		$('ul.preview li').each(function() {
			if ($(this).find('a').attr('class') == activeId) {
				$(this).addClass('active');
			} else {
				$(this).removeClass('active');
			}
		});
		
		$('ul.bio li').each(function() {
			($(this).attr('class') == activeId) ? $(this).fadeIn() : $(this).hide();
		});
		
		return false;
	});
	
	//////////////////////
	//  Blog functions  //
	//////////////////////
	
	// get nav scroll position and maintain after refresh
	
	var topCk = document.cookie;
	
	if (topCk.indexOf("!~") != 0) {
		var intS = topCk.indexOf("!~");
		var intE = topCk.indexOf("~!");
		var strPos = topCk.substring(intS+2, intE);
		$('#blogNav').scrollTop(strPos);
	}
	
	$('#blogNav a').click(function() {
		var intY = $('#blogNav').scrollTop();
		document.cookie = "yPos=!~" + intY + "~!";
	});
	
    // activate clicked thumbnail
	// load active image in gallery div
	
	$('#blogContent .col01 ul li div').click(function() {
		var id = $(this).parent().attr('id');
		var img = $(this).children('a').attr('rel');
		
		$('#blogContent .col01 ul li').each(function(i) {
			($(this).attr('id') == id) ? $(this).addClass('active') : $(this).removeClass('active');
		});
		
		$('#gallLrg img').hide();
		$('#gallLrg img').attr('src', img);
		$('#gallLrg img').fadeIn(300);
		
	});
	
}

function objCheck(arr) {
	var obj = {};
	for (var i = 0; i < arr.length; i++) {
		obj[arr[i]] = '';
	}

	return obj;
}

// ------------------------------------------------------------
//
// Event listener
//
// ------------------------------------------------------------

SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);

