/*
-----------------------------------------------
TheGlendaleGroup.com
Script: vdwProjects.js
Author: Ben Glassman
Organization: Vermont Design Works
Created: 23 July 2009
----------------------------------------------- */

vdwProjects = {
	current_project_id : 0,
	loading : false,
	delay : 10000,
	init:function() {
		if ($jq('#module-projects').length > 0) { vdwProjects.initModule(); }
		if ($jq('#project-details').length > 0) { vdwProjects.initDetails(); }
	},
	initModule : function() {
		var matches = $jq('#project-details-container .project-details').attr('id').match(/project-details-(\d+)/);
		vdwProjects.current_project_id = matches[1];
		$jq('#projects-gallery .project-details').each(function() {
			var matches = $jq(this).attr('href').match(/project_id=(\d+)/);
			if (matches[1] == vdwProjects.current_project_id) {
				vdwProjects.current_project_index = $jq(this).parents('ul').eq(0).find('li').index($jq(this).parent());
			}
		});
		$jq('#projects-gallery').jcarousel({
			scroll : 1,
			wrap : 'both'
		});
		$jq('#projects-gallery .project-details').click(function(e) {
			e.preventDefault();
			var matches = $jq(this).attr('href').match(/project_id=(\d+)/);
			var project_id = matches[1];
			vdwProjects.ajaxLoadProjectDetails($jq(this), project_id);
		});
		vdwProjects.timeout = setTimeout(vdwProjects.projectDetailsTimer, vdwProjects.delay);
	},
	initDetails : function() {
		$jq('#project-images-gallery').jcarousel({
			scroll : 1,
			wrap : 'null'
		});		
	},
	ajaxLoadProjectDetails : function($this, project_id) {
		if (vdwProjects.loading || vdwProjects.current_project_id == project_id) { return; }
		clearTimeout(vdwProjects.timeout);
		vdwProjects.loading = true;
		vdwProjects.current_project_id = project_id;
		vdwProjects.current_project_index = $this.parents('ul').eq(0).find('li').index($this.parent());
		$jq.ajax({
			type : 'POST',
			url : '/ajax-handlers/projects',
			cache : false,
			data : {
				projects_mode : 'details',
				limit : 1,
				details_tpl : 'projects_module_details_tpl',
				image_size : 'full',
				project_id : project_id
			},
			success : function(html) {
				$jq('#project-details-container').html(html);
				vdwProjects.loading = false;
				vdwProjects.timeout = setTimeout(vdwProjects.projectDetailsTimer, vdwProjects.delay);
			}
		});
	},
	projectDetailsTimer : function() {
		clearTimeout(vdwProjects.timeout);
		var index = (vdwProjects.current_project_index < ($jq('#projects-gallery li').length - 1)) ? vdwProjects.current_project_index + 1 : 0;
		$jq('#projects-gallery li').eq(index).find('.project-details').click();
	}
}
$jq(document).ready(vdwProjects.init);