//var $ = jQuery.noConflict();  
var initialWidth = 165;
var scroller;

$(document).ready(function(){

	try {
  		document.execCommand("BackgroundImageCache", false, true);
	} catch(e) {
		
	}


	if(cms_page_id == "disabled"){
	
		$(".page_content").each(function(){
		
			if($(this).attr("id") != "about-us"){
				$(this).remove();
			}
		
		});
		
	} 
	
	initCarousel();
	initNavBar();
	initSubNavBar();
	initPanFade();
	initOurWork();
	initContactUs();
	initEditablePage();
	
});

$(window).load(function(){
	applyTitles();
});

var loops = 0;

function initCarousel(){
	
	$("#carousel img").css('display', 'none');
	$("#carousel img").each(function(i){
		var left = $(this).attr('longdesc') + "px";
		$(this).css('left', left);
		if(i == 0){
			$(this).css('display', 'block').addClass('active');
		}
	});

	//$("#carousel img:first").css('display', 'block').addClass('active');
	
	var images = $("#carousel img");
	
	$("#image_left").click(function(e){
		e.preventDefault();
		var selectedIndex = 0;
		$(images).each(function(i){
			if($(this).hasClass('active')){
				selectedIndex = i;
			}
		});
		
		var nextIndex = selectedIndex - 1;
		if(nextIndex < 0){
			nextIndex = images.length - 1;
		}
		
		$("#carousel img").removeClass('active');
		$("#carousel img:eq(" + nextIndex + ")").addClass('active');
		$("#carousel img:not(.active)").fadeOut('slow');
		$("#carousel img.active").fadeIn('slow');
		
	});
	
	$("#image_right").click(function(e){
		e.preventDefault();
		
		var selectedIndex = 0;
		$(images).each(function(i){
			if($(this).hasClass('active')){
				selectedIndex = i;
			}
		});
		
		var nextIndex = selectedIndex + 1;
		if(nextIndex >= images.length){
			nextIndex = 0;
		}
		
		$("#carousel img").removeClass('active');
		$("#carousel img:eq(" + nextIndex + ")").addClass('active');
		$("#carousel img:not(.active)").fadeOut('medium');
		$("#carousel img.active").fadeIn('medium');
		
	});
	
}

function initEditablePage(){
	
	if(cms_page_id == ""){
		//not owner
	} else {
		
		if(!$.browser.msie){
			alert("You are about to begin using our CMS. The 'about us' page is editable - click OK to get started.");	
		}
		
		$('.editable').editable('index.php?id=118', { 
    	    indicator : '<img id="loading_ajax" src="web_assets/css/images/loading_web.gif">',
    	    type      : 'wysiwyg',
    	    width     : 500,
		    height    : 300,
    	    onblur    : 'ignore',
    	    submit    : 'Save',
    	    cancel    : 'Cancel',
    	    id   : 'tv_id',
    	    submitdata : {
    	    		doc_id: cms_page_id
    	    	}

		});
		$(".subpages").css('position', 'relative');
		startEditing();
		
	}
	
}

function startEditing(){
	$('#about-us .inner_content_column').trigger('click');
	$("#about-us .inner_content_column").css('z-index', '0');
	$("#about-us .inner_content_column p").attr("title", "Click to edit");
}

function applyTitles(){
	
	$("a.bold").attr("title", "Bold");
	$("a.italic").attr("title", "Italic");
	$("a.underline").attr("title", "Underline");
	$("a.insertUnorderedList").attr("title", "Insert Unordered List");
	$("a.createLink").attr("title", "Add a link");
	$("a.insertImage").attr("title", "Add an image");
	$("a.increaseFontSize").attr("title", "Increase the font size");
	$("a.decreaseFontSize").attr("title", "Decrease the font size");
	$("a.removeFormat").attr("title", "Remove formatting");
	
}

function tryCMS(){
	
	var user_name = window.prompt("What is your name? We'll create a new page for you to edit.", "");
	if(user_name != '' && user_name != null){
		//tryCMS();
		window.location.href = "index.php?&id=111&action=create&username=" + user_name;
	} else {
		
	}
	
}

function initContactUs(){

	$(".text_input").val("");

	$("#submit").click(function(e){
		e.preventDefault();
		var required_fields = $("#contact_us_form .text_input");
		var count_errors = 0;
		$(required_fields).each(function(){
		
			if($(this).val() == ""){
				$(this).animate({
					backgroundColor: '#ff0000'
				}, 400).animate({
					backgroundColor: '#ffffff'
				}, 400);
				count_errors++;
			}
		
		});
		
		if(count_errors == 0){
			$("#contact_us_form").submit();
		}
				
	});
}

function stopClients(){
	$("#client_scroller").html(scroller);
}

function initOurClients(){

	scroller = $("#client_scroller").html();

	$("#client_list").simplyScroll({
			className: 'vert',
			horizontal: false,
			frameRate: 24,
			speed: 2,
			autoMode: 'loop'
	});
	
	$("#client_list a.has_testimonial_1").click(function(e){
		e.preventDefault();
		
		if($(this).siblings('.testimonial').text() == ""){
			
		} else {
			var clone = $(this).siblings('.testimonial').clone();
			$("#client_testimonials").empty().css('opacity', '0');
			$("#client_testimonials").html($(clone));
			$("#client_testimonials").animate({
				opacity: 1
			});
			$("#client_testimonials .testimonial").animate({
				paddingLeft: '5px'
			});
			$("#client_testimonials .testimonial cite").animate({
				paddingRight: '0px'
			});
			
		}
		
	});
	
	$("#client_list a.has_testimonial_1").trigger('click');
	
	$("#client_list a.has_testimonial_0").click(function(e){
		e.preventDefault();
	});
	
}


function initOurWork(){
	
	$(".projects").each(function(i){
		if($("li.hide_first_Yes", this).length == 1){
			$("li", this).css('display', 'none');
		}
	});

	
	$(".projects").css('opacity', '0').css('display', 'block');
	
	$(".client_link").click(function(e){
		e.preventDefault();
		$("#project_carousel").empty();
		$(".client_link").removeClass('active');
		$(this).addClass('active');
		
		$(".projects:not(#projects_" + $(this).attr('id') + ")").animate({
			opacity: 0,
			right: '5px'
		}).css('z-index', '0');
		
		$("#projects_" + $(this).attr('id')).animate({
			opacity: 1,
			right: '0px'
		}).css('z-index', '1');;
	//var selector = $("#projects_" + $(this).attr('id')
		$("#projects_" + $(this).attr('id') + " a.display_0:eq(" + initialIndex + ")").trigger('click');
		//console.log("#projects_" + $(this).attr('id') + " a.display_0:eq(" + initialIndex + ")");
		initialIndex = 0;
		
	});
	
	$('.projects a.display_1').click(function(e){
		e.preventDefault();
	});
	
	$('.projects a.display_0').click(function(e){
		//alert($(this).attr("id"));
		e.preventDefault();
		$('.projects a').removeClass('active');
		$(this).addClass('active');
		var url = $(this).attr('href');
		
		$("#project_carousel").html('<img src="web_assets/css/images/loading_web.gif" class="loader" />');
		
		
		$.get(url, 
			{
				ajax: 'true'
			},
			function(data){
			
			$("#project_carousel").html(data);
			initProjectCarousel();
		});


		
	});
	
}


function outer(){

	var a = 0;

	function inner(){
		if(a===$('#project_carousel img').length){return;}
			a++;
			$('#project_carousel img').eq(a).fadeIn(210,function(){fader();});
		}
	
	return inner;
}

function fadeChain(selector, index){
	if(index === $(selector).length){
		return;
	} else {
		$(selector).eq(index).animate({
			opacity: 1
		}, 210, "swing", function(){ 
			index++;
			fadeChain(selector, index) ;
		});
	}
}



function initProjectCarousel(){
	
	var images = $(".project_images img").css('opacity', '0').css('display', 'block');
	
	$(".project_images img:eq(0)").animate({
			opacity: 1,
			marginLeft: '10px'
		}).addClass('active');
	
	if(images.length > 1){
		$("#carousel_links a").css('display', 'block');
		
		//create thumbs?
		var filmstrip = "<div id='filmstrip'>" + $(".project_images").html() + "</div>";
		$("#project_carousel").append(filmstrip);
		$("#filmstrip img").css('opacity', 1);
		$("#filmstrip img:eq(3)").addClass('endImg');
		$("#filmstrip img").each(function(i){
			$(this).attr('src', $(this).attr('longdesc'));
			$(this).click(function(e){
				e.preventDefault();
				if(i == 0){
					$("#current_image").html('2');
					$("#prev_image").trigger('click');
				} else {
					$("#current_image").html(i);
					$("#next_image").trigger('click');
				}
				
			});
		
		});
		//fadeChain("#filmstrip img", 0);
		//$("#project_carousel img")
	}
	
		
	$("#total_images").html(images.length);
	
	$("#prev_image").click(function(e){
		e.preventDefault();
		var currentIndex = parseInt($("#current_image").text());
		if(currentIndex == 1){
			nextIndex = images.length - 1;
		} else {
			nextIndex = currentIndex - 2;
		}
		//$(".project_images img.active").fadeOut().removeClass('active');
		$(".project_images img.active").animate({
			opacity: 0,
			marginLeft: '0px'
		}).removeClass('active');
		//$(".project_images img:eq(" + nextIndex + ")").fadeIn().addClass('active');
		$(".project_images img:eq(" + nextIndex + ")").animate({
			opacity: 1,
			marginLeft: '10px'
		}).addClass('active');
		$("#current_image").html(nextIndex + 1);
		
		if($(".project_images img.active:first").attr('alt') != $("#project_description").text()){
			
			$("#project_carousel h4").animate({ opacity: 0}, '', '', function(){
				$("#project_description").html($(".project_images img.active:first").attr('alt'));
			}).animate({opacity: 1});
		
		}
		
	});
	
	$("#next_image").click(function(e){
		e.preventDefault();
		var currentIndex = parseInt($("#current_image").text());
		if(currentIndex == images.length){
			nextIndex = 0;
		} else {
			nextIndex = currentIndex;
		}
		$(".project_images img.active").animate({
			opacity: 0,
			marginLeft: '0px'
		}).removeClass('active');
		
		$(".project_images img:eq(" + nextIndex + ")").animate({
			opacity: 1,
			marginLeft: '10px'
		}).addClass('active');
		$("#current_image").html(nextIndex + 1);
		
		if($(".project_images img.active:first").attr('alt') != $("#project_description").text()){
			
			$("#project_carousel h4").animate({ opacity: 0}, '', '', function(){
				$("#project_description").html($(".project_images img.active:first").attr('alt'));
			}).animate({opacity: 1});
		
		}
		
	});
	
	for(var x = 0; x < thumbIndex; x++){
		$("#next_image").trigger('click');
	}

	
}

function hashCheck(){

	
	setTimeout(function(){
		var hash = window.location.hash;
		if(hash == ""){
			$("#navigation .active a").trigger('click');
		} else {
			path = hash.replace('#/','');
			revertToPage(path);
			if(cms_page_id == "disabled"){
				$("#navigation a").each(function(){
				
					if($(this).attr("id") != "nav_about-us"){
						$(this).unbind('click');
						
						$(this).click(function(e){
							e.preventDefault();
						});
					}
				
				});
				
			}
		}	
	}, 1500);
	
}

var thumbIndex = 0;

function revertToPage(path){
	pages = path.split('/');
	var triggerClick = pages[0];
	
		if(pages.length >= 2){
			var secondary = $("#" + pages[1]);
			
			if(pages.length == 3){
				thumbIndex = parseInt(pages[2]) - 1;
			}
			
			if(secondary.length > 0){
				initialIndex = 0;
				
				$(secondary).parents('.projects').find('a.display_0').each(function(i){
					if($(this).attr('id') == $(secondary).attr('id')){
						initialIndex = i;
					}
				});
				//$(secondary).trigger('click');
			}
			
			
		}
	
	var target = $("#nav_" + triggerClick).trigger('click').length;
	
	if(target == 0){
		//there's 'dirt' in the hash... revert to a normal page load.
		$("#navigation .active a").trigger('click');
		
		return;
	}
}

function initSubNavBar(){

	$('.subnavigation a').animate({ opacity: 0.5}, 150);

	$('.subnavigation a').click(function(e){
		e.preventDefault();
		
		if(!$(this).parents('li').hasClass('active')){
		
			var section = $(this).parents('.page_content').attr('id');
			var revealPage = $(this).attr('id').replace(/nav_/,'');
			revealSubpage(revealPage, section);
		
			$('.subnavigation li').removeClass('active');
			$(this).parents('li').addClass('active');
			$('.subnavigation a:not(#' + $(this).attr('id') + ')').animate({ opacity: 0.5}, 0);
			$(this).animate({ opacity: 1}, 0);
		
		}
	});
	
	$('.subnavigation a').hover(
		function(){
			if(!$(this).parents('li').hasClass('active')){
				$(this).animate({ opacity: 1}, 150);
			}
			
		}, function(){
			if(!$(this).parents('li').hasClass('active')){
				$(this).animate({ opacity: 0.5}, 150);
			}
		}
	);

}

function breadcrumb(link){
	//indicates where we are within the site, visually with active states and the red ipulse logo extends.
	$("#navigation h1, #navigation_top li, .subnavigation li").removeClass('active');
	
	if(link == 'index'){
		$('#logo').addClass('active');
		var width = initialWidth;
	} else {
		$(link).parents('li').addClass('active');
		var width = $(link).position().left + $(link).width();
	}
	
	$("#DISABLEDlogo a").animate({
		width: width + 'px'
	}, 1000, "easeOutBounce");
	
}

function initNavBar(){
	initialWidth = $("#logo a").width();
	
	$("#navigation_top a").each(function(i, elem){
	
		$(this).click(function(e){
			
			$('.subnavigation a').animate({ opacity: 0.5}, 150);
		
			e.preventDefault();
			breadcrumb($(this));
			
			var revealPage = $(this).attr('id').replace(/nav_/,'');
			reveal(revealPage);
		});
	
	});
	
	$("#logo a").click(function(e){
	
		$('.subnavigation a').animate({ opacity: 0.5}, 150);
	
		e.preventDefault();
		breadcrumb('index')
		reveal('index');
	});
	
}

function initPanFade(){
	//on load of document, load in the 'active' page and the navbar.
	$(".page_content, .subpage").css('opacity', '0').css('display', 'block');
	
	$("#navigation, #footer").css('display', 'none').fadeIn('slow');
	hashCheck();//tells us where to 'click' for deeplinking.
	
}

function revealSubpage(page, section){
	transitionLevelOne(section);
	var targetNavBarLink = $("#nav_" + section);
	breadcrumb(targetNavBarLink);
	$("#" + section + ".page_content").animate({
		left: '5px',
		opacity: 1
	}).css('z-index', '1');
	//bring in the section (if it isnt in already)
	
	$("#" + section + " .inner_content_column").stop().animate({
		opacity: 0,
		left: '0px'
	}).css('z-index', '0');
	//fade out the section default (if it isnt in already)
	
	if(section == 'about-us'){
		$("#" + page).animate({
			left: '5px',
			opacity: 1
		}).css('z-index', '1');
		
		
	}
	
	window.location.hash = "/" + section + "/" + page;
}

var initialIndex = 0;

function reveal(page){
	//each page may or may not have a different loading sequence.

	transitionLevelOne(page);	
	
	if(page == "index"){
		$("#index.page_content, #index.page_content .inner_content_column").animate({
			left: '5px',
			opacity: 1
		}).css('z-index', '1');
		stopClients();
	}
	
	if(page == "about-us"){
		$("#about-us.page_content, #about-us.page_content .inner_content_column").animate({
			left: '5px',
			opacity: 1
		}).css('z-index', '1');
	}
	
	if(page == "our-works"){
		$("#our-works.page_content").animate({
			left: '5px',
			opacity: 1
		}).css('z-index', '1');
		$("#our-works a.client_link:eq(0)").trigger('click');
	}
	
	if(page == "contact-us"){
		$("#contact-us.page_content").animate({
			left: '5px',
			opacity: 1
		}).css('z-index', '1');
	}
	
	if(page == "our-clients"){
		$("#our-clients.page_content, #our-clients.page_content .inner_content_column").animate({
			left: '5px',
			opacity: 1
		}).css('z-index', '1');
		initOurClients();
	}
	
	window.location.hash = "/" + page;
	applyTitles();
}

function transitionLevelOne(page){
	$("#" + page).css('height', '500px');

	$(".page_content:not(#" + page + ")").animate({
		opacity: 0,
		left: '0px'
	}).css('z-index', '0').css('height', '0px');
	
	$(".subpage").animate({
		opacity: 0,
		left: '0px'
	}).css('z-index', '0');
}

jQuery.extend( jQuery.easing,
{
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

/*
 * simplyScroll 1.0.4 - a scroll-tastic jQuery plugin
 *
 * http://logicbox.net/jquery/simplyscroll
 * http://logicbox.net/blog/simplyscroll-jquery-plugin
 * http://plugins.jquery.com/project/simplyScroll
 *
 * Copyright (c) 2009 Will Kelly - http://logicbox.net
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Last revised: 03/07/2009 21:13
 *
 */

(function($) {

$.fn.simplyScroll = function(o) {
	return this.each(function() {
		new $.simplyScroll(this,o);
	});
};

var defaults = {
	className: 'simply-scroll',
	frameRate: 24, //No of movements per second
	speed: 1, //No of pixels per frame
	horizontal: true,
	autoMode: 'off', //disables buttons 'loop','bounce'
	pauseOnHover: true,
	startOnLoad: true, //use this if having rendering problems (safari 3 + Mac OSX?)
	localJsonSource: '', //format [{"src":"images/pic.jpg","title":"title","link":"http://"},{etc..}]
	flickrFeed: '',
	jsonImgWidth: 240,
	jsonImgHeight: 180
};
	
$.simplyScroll = function(el,o) {
	
	var self = this;
	
	this.o = $.extend({}, defaults, o || {});
	this.auto = this.o.autoMode!=="off" ? true : false;
	
	//called on ul/ol/div etc
	this.$list = $(el);
	
	//generate extra markup
	this.$list.addClass('simply-scroll-list')
		.wrap('<div class="simply-scroll-clip"></div>')
		.parent().wrap('<div class="' + this.o.className + ' simply-scroll-container"></div>');
	
	if (!this.o.auto) { //button placeholders
		this.$list.parent().parent()
		.prepend('<div class="simply-scroll-forward"></div>')
		.prepend('<div class="simply-scroll-back"></div>');
	}
	
	
	
	//load image data
	if (this.o.flickrFeed) {
		$.getJSON(this.o.flickrFeed + "&format=json&jsoncallback=?",
			function(data) {
				json = [];
				$.each(data.items, function(i,item) {
					json.push({
						"src": item.media.m,
						"title": item.title,
						"link": item.link
					});
				});
				self.renderData(json);
			}
		);
	} else if (this.o.localJsonSource) {
		$.getJSON(this.o.localJsonSource,
			function(json) {
				self.renderData(json);
			}
		);
	} else {
		
		if (!this.o.startOnLoad) {
			//this.moveForward();
			this.init();
		} else {
			this.init();
			//wait for load before completing setup
			//$(window).load(function() { self.init();  });
		}
		
	}
		
};
	
$.simplyScroll.fn = $.simplyScroll.prototype = {};

$.simplyScroll.fn.extend = $.simplyScroll.extend = $.extend;

$.simplyScroll.fn.extend({
	init: function() {
		//shortcuts
		this.$items = this.$list.children();
		this.$clip = this.$list.parent();
		this.$container = this.$clip.parent();

		if (!this.o.horizontal) {
			this.itemMax = this.$items[0].offsetHeight; //this.$items[0].offsetHeight;
			this.clipMax = this.$clip.height(); //this.$clip[0].offsetHeight;
			this.dimension = 'height';			
			this.moveBackClass = 'simply-scroll-btn-up';
			this.moveForwardClass = 'simply-scroll-btn-down';
		} else {
			this.itemMax = this.$items[0].offsetWidth;
			this.clipMax = this.$clip.width();			
			this.dimension = 'width';
			this.moveBackClass = 'simply-scroll-btn-left';
			this.moveForwardClass = 'simply-scroll-btn-right';
		}
		
		this.posMin = 0;
		this.posMax = this.$items.length * this.itemMax;
		this.$list.css(this.dimension,this.posMax +'px');
		
		if (this.o.autoMode=='loop') {
			var addItems = Math.ceil(this.clipMax / this.itemMax);	
			this.$items.slice(0,addItems).clone(true).appendTo(this.$list);
			this.posMax += (this.clipMax - this.o.speed);
			this.$list.css(this.dimension,this.posMax+(this.itemMax*addItems) +'px');
		}
		
		this.interval = null;	
		this.intervalDelay = Math.floor(1000 / this.o.frameRate);
		
		//ensure that speed is divisible by item width
		while (this.itemMax % this.o.speed !== 0) {
			this.o.speed--;
			if (this.o.speed===0) {
				this.o.speed=1; break;	
			}
		}
		
		var self = this;
		this.trigger = null;
		this.funcMoveBack = function() { self.trigger=this;self.moveBack(); };
		this.funcMoveForward = function() { self.trigger=this;self.moveForward(); };
		this.funcMoveStop = function() { self.moveStop(); };
		this.funcMoveResume = function() { self.moveResume(); };
		
		if (this.auto) {
			if (this.o.pauseOnHover) {
				this.$clip.hover(this.funcMoveStop,this.funcMoveResume);
			}
			this.moveForward();
		} else {
			this.$btnBack = $('.simply-scroll-back',this.$container)
				.addClass('simply-scroll-btn' + ' ' + this.moveBackClass + ' ' + 'disabled')
				.hover(this.funcMoveBack,this.funcMoveStop);
			this.$btnForward = $('.simply-scroll-forward',this.$container)
				.addClass('simply-scroll-btn' + ' ' + this.moveForwardClass)
				.hover(this.funcMoveForward,this.funcMoveStop);
		}
	},
	moveForward: function() {
		
		var self = this;
		this.movement = 'forward';
		if (this.trigger !== null) {
			this.$btnBack.removeClass('disabled');
		}
		self.interval = setInterval(function() {
			if (!self.o.horizontal && self.$clip[0].scrollTop < (self.posMax-self.clipMax)) {
				self.$clip[0].scrollTop += self.o.speed;
			} else if (self.o.horizontal && self.$clip[0].scrollLeft < (self.posMax-self.clipMax)) {
				self.$clip[0].scrollLeft += self.o.speed; 
			} else if (self.o.autoMode=='loop') {
				self.resetPos();
			} else {
				self.moveStop(self.movement);
			}
		},self.intervalDelay);
	},
	moveBack: function() {
		var self = this;
		this.movement = 'back';
		if (this.trigger !== null) {
			this.$btnForward.removeClass('disabled');
		}
		self.interval = setInterval(function() {
			if (!self.o.horizontal && self.$clip[0].scrollTop>0) {
				self.$clip[0].scrollTop -= self.o.speed;
			} else if (self.o.horizontal && self.$clip[0].scrollLeft>0) {
				self.$clip[0].scrollLeft -= self.o.speed;
			} else if (self.o.autoMode=='loop') {
				self.resetPos();
			} else {
				self.moveStop(self.movement);
			}
		},self.intervalDelay);
	},
	moveStop: function(moveDir) {
		clearInterval(this.interval);	
		if (this.trigger!==null) {
			if (typeof moveDir != "undefined") {
				$(this.trigger).addClass('disabled');
			}
			this.trigger = null;
		}
		if (this.auto) {
			if (this.o.autoMode=='bounce') {
				moveDir == 'forward' ? this.moveBack() : this.moveForward();
			}
		}
	},
	moveResume: function() {
		this.movement=='forward' ? this.moveForward() : this.moveBack();
	},
	resetPos: function() {
		if (!this.o.horizontal) {
			this.$clip[0].scrollTop = 0;
		} else {
			this.$clip[0].scrollLeft = 0;
		}
	},
	renderData: function(json) {
		if (json.length>0) { //render json data
			var self = this;
			$.each(json, function(i,item) {
				$("<img/>").attr({
					src: item.src,
					title: item.title,
					alt: item.title,
					width: self.o.jsonImgWidth,
					height: self.o.jsonImgHeight
				}).appendTo(self.$list);
			});
			this.init();
		}
	}
});
		  
})(jQuery);
