var _urlid;

$(document).ready(function(){
	if(!hasCSS()){return false;}
 
	$('.window').draggable({stop: function(event, ui){ updateState($(this))}, handle:'div.handle', cursor:"move" ,stack:{ group: $('.window'), min:1000}});	
	
	$('.icon:not(.inactive)').draggable({stop: function(event, ui){ updateState($(this))},start: function(event, ui){ highlight($(this))},stack:{ group: $('.icon'), min:50}})

	$(window).resize(function(){
	  layout();
	});
		
	$('.window').resizable({minWidth:860, minHeight:580, handles:'se'});
	$('.window').hide();

	urlloc =  window.location.hash.replace("#/","");	
	qi = urlloc.split('?');
		
	_urlid = qi[0];
	


	if(window.location.hash==''){
		
		
	  
	var _gaq = _gaq || [];
	  _gaq.push(['_setAccount', 'UA-2210974-1']);
	  _gaq.push(['_trackPageview']);

	  (function() {
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
	  })();
		
	};
	
	
	getState();
	renderState();
	layout();
	subscription();
	parseUrl();

	$('h1#logo').click(function(){
		closeAllWindows();
		$('ul#menu li.highlight').removeClass('highlight');
		$('.icon').draggable('enable').removeClass('inactive active highlight');
		return false;
	})


	$('ul#menu li.text a, ul#menu li.section-10.proj a').click(function(){
		
		var id = '.window#win_' + ($(this).attr('rel')).toString();				
		launchWindow($(id));
		return false;
				
	})
	
	$('ul#menu li.proj a:not(ul#menu li.proj.section-10 a)').click(function(){
		if($(this).parent().hasClass('highlight')){
			$(this).parent().removeClass('highlight');

			$('.icon').draggable('enable').removeClass('inactive active highlight');
			return false;
		}
		
		closeAllWindows();
		
		var tag = 'tag_'+($(this).attr('title')).toString();
		$('.icon:not(.'+tag+')').addClass('inactive').draggable('disable');
		
		$('.icon.'+tag).removeClass('inactive highlight').addClass('active').draggable('enable').each(function(){
			$(this).css('zIndex', maxZ($('.icon'))+1);
			$(this).children('div.screen').remove();
		});
		
		$('ul#menu li.highlight').removeClass('highlight');
		$(this).parent().addClass('highlight');
		return false;

	})
	
	$(".window a.x").click(function(){
		closeWindow($(this).parent());
		return false;
	})
	
		
	$(".icon").click(function(){
		if($(this).hasClass('inactive')) return false;
		var id = '.window#win_' + ($(this).attr('rel')).toString();
		highlight($(this));	
		launchWindow($(id));	
		return false;
	});


	
	$('a.thumb').click(function(){
		
		var thumblist =  $(this).parents('ul.thumbs');
		var displaydiv = $(this).parents('div.exhibit').find('div.media div.mediadisplay').eq(0);
		var captiondiv = $(this).parents('div.exhibit').find('div.media div.caption').eq(0);
		var src = $(this).attr('href');

		
		if ( $(this).parent().hasClass('m4v')||$(this).parent().hasClass('mov') ){
			
			video($(this));
				
		}else{		
			var fw = $(this).children('img').attr('fullwidth');

		  var img =   '<img src="' + $(this).attr('href') + '" width="'+fw+'" />';
			
			
			displaydiv.html(img);
		}
		
				  
	 	var title = '<span class="title">'+$(this).attr('title')+'</span>';
	 	var caption = '<span class="caption">'+$(this).attr('rel')+'</span>';
	 		 
	 	
	 	captiondiv.html(title+caption);
		 
		thumblist.find('li a.thumb.active').removeClass('active');
		$(this).addClass('active');

		return false;
		
		
	})

		$('select.ship').change(function(){
			
		   form = $(this).parent().parent().parent();
			
			val = form.find('[name=amount_1]').val();
			qty = $(this).val();
			total = val*1 + qty*1 ;
			
			
			
			form.find('.total').text('$'+total+" CAD");
		})

						




})





function windowSize(){
	
	return {w:$(window).width(), h:$(window).height()}
}


function newWindow(){
	
	var bounds = windowSize()
	var new_w = 860;
	var new_h = Math.max(bounds.h*.85, 590);


	var new_x = (bounds.w - new_w) /2;
	var new_y = Math.max((bounds.h-new_h)/4,0);
	
	
	
	while( !isPosAvail(new_x,new_y) ){		
		new_x = new_x +15;
		new_y =+ new_y + 15;		
	}
		
	
	
	return {x: new_x  ,y: new_y , w:new_w, h:new_h}
}


function isPosAvail(x,y){
	
	var flag = false;
	$('.window.open').each(function(){
		var p = $(this).position();
		
		if( Math.floor(x) == p.left || y== p.top) {flag=true;}		
		})
    
     if(flag==true) return false;

     return true;
	
}

function getState(){
	
  
	 if (getCookie('_state')){
	 		state = eval(getCookie('_state'));					
	 	}else{
		state = eval(state);
	}	



		
}




function distributeIcons(){
	
	var tilesize =140;
	var field = windowSize() ;
	var xtiles = Math.floor(field.w/tilesize) ;
	var ytiles = Math.floor(field.h/tilesize) ;
	var map = [];
    
	for(var i = 0; i < xtiles*ytiles;i++ ){
		map.push(i);
	}		
		
	$('.icon').each(function(){
		var tile = map.splice(Math.floor ( Math.random()*map.length ), 1 );
		var tiley = tilesize * ( Math.floor(tile/xtiles) ) + (120 - $(this).height());
		var tilex = tilesize * ( tile % xtiles ) ;
    $(this).css({'top':tiley,'left':tilex});
	
	}) 	
}


function renderState(){	
	
	if(window.location.hash){
		var urlid = '#win_'+_urlid;
		
		$('.window').each(function(){
		    removeFromState($(this));
		})

		launchWindow($(urlid),1);
	}


if(!state) return false;

for (var i = state.length - 1; i >= 0; i--){
		
		if(state[i]._id=='' || state[i]._id==null ) continue;
		var _o = $('#'+state[i]._id);

	    _o.css('top',state[i]._y);
		_o.css('left',state[i]._x);
		_o.css('zIndex', state[i]._z);
 		
	 	if(state[i]._class=='window') {
	 		_o.width(state[i]._w);
	 		_o.height(state[i]._h);
		    _o.show().addClass('open');
	    }			 	
	}	
}


function layout(){
	
	var winSize = windowSize();
	
	$("body").height(winSize.h);	
	$("#desktop").height(winSize.h-49);
	$('#desktop').width(winSize.w-10);
	$('.window.open, .icon').each(function(){
		bounds($(this));
	});	
}


function bounds(_o){
    
	var w = _o.width();
	var h = _o.height();
	var xy= _o.position();
	var x = xy.left;
	var y = xy.top;	
	var bounds = windowSize();
		
	if(_o.hasClass('.icon')){
		if(x+100>bounds.w)_o.css('left',bounds.w-w-50)
		if(x<12) _o.css('left',0);

		if(y+h>bounds.h) _o.css('top',bounds.h-h-70); 
		if(y<4) _o.css('top', 4);
		return;
	}
	
	if(x+50>bounds.w) {_o.css('left',bounds.w-100)}
	if(x+w<100) {_o.css('left',100	-w);}
	
	if(y>bounds.h-120){ _o.css('top',bounds.h-120) }
	if(y<0) {_o.css('top', 0);}
	
}
			
function updateState(_o){
	
 bounds(_o);
 var p = _o.position();
 var w = 0;
 var h = 0;
 var c = 'icon';

 if(_o.hasClass('window')){
	w = _o.width();
	h = _o.height();
	c = 'window';
	
	if(!_o.hasClass('open')) return 
	
 }
 
 var item = {_id:_o.attr("id"), _x:p.left, _y:p.top, _z:_o.css('z-index'), _w:w, _h:h, _class:c }



 for (var i=0; i < state.length; i++) {
		if(item._id==state[i]._id){
			state.splice(i,1);
		}			
	}
  	
  state.push(item);

  return;
 
}

function removeFromState(_o){

	
    var window_id = _o.attr('id');
	for (var i=0; i < state.length; i++) {
		if(window_id==state[i]._id){
			state.splice(i,1);
			return;
		}			
	}
}

function saveState(){
	var newstate = JSON.stringify(state);
	//setCookie("_state", newstate, 90);
}


function maxZ(_o){
	var maxz = Math.max.apply(Math, $.map(_o,function(e,n){   
		 return parseInt($(e).css('zIndex'))||1000
		}))
	return maxz;
}






function closeAllWindows(){
	
	$('.window.open').each(function(){
		closeWindow($(this));
	
	})
}


function closeWindow(_o){
	_o.hide().removeClass('open');
	removeFromState(_o);
	
	var thiswindow = _o.attr('id').replace('win_','');	
	var urlwindow =  _urlid;	
	if(thiswindow==urlwindow) { window.location.hash = '' };			
	
}

function launchWindow(_w,omiturl){	

	if( _w.css('display')!='none') {_w.css('zIndex',maxZ($('.window'))+1); return;}
	var w = newWindow();
	_w.css('top',w.y);
	_w.css('left',w.x);
	_w.css('zIndex',maxZ($('.window'))+1);
	_w.height(w.h);
	_w.width(w.w);	
	_w.show().addClass('open');
	_w.children('div.exhibit').scrollTop(0);
	updateState(_w,'window');
	//alert(omiturl);
	if(omiturl==undefined){
		window.location.hash = '/'+_w.attr('id').replace("win_", "");
	}
	
	if( _w.find('li a.active').parent().hasClass('m4v')||_w.find('li a.active').parent().hasClass('m4v') ){video(_w.find('li a.active'))}
	
	
	  var _gaq = _gaq || [];
	  _gaq.push(['_setAccount', 'UA-2210974-1']);
	  _gaq.push(['_trackPageview']);

	  (function() {
	    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
	  })();
	

}





function highlight(_o){
	$('.icon.highlight').removeClass('highlight');
	_o.addClass('highlight');
}






function sortIcons(){
	
}





function getCookie(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(c_name + "=")

		if (c_start != -1)
		{ 
			c_start = c_start + c_name.length + 1 
			c_end = document.cookie.indexOf(";", c_start)
			
			if (c_end == -1) c_end = document.cookie.length
			return unescape(document.cookie.substring(c_start, c_end))
		} 
	}
	return 0;
}

function setCookie(c_name,value,expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) +
	((expiredays==null) ? "" : ";expires=" + exdate.toGMTString()) + '; path=/';
}



function subscription(){
			var def = "your@email"	;
			$('#e').focus(function(){
				var val = $('#e').val();
				$('#e').val(inputrewrite(val,def));
			});
			$('#e').blur(function(){
				var val = $('#e').val();
				$('#e').val(inputrewrite(val,def));
			});

			$('#email_submit').click(function(){
				var val = $('#e').val();
				var container = $('#e').parent();
				if(!echeck(val))return false;
				$('#e').fadeOut('slow');
				container.empty().append("Please Wait...");			
				container.load("/subscribe.php?e="+val);
			})	
		}

		function inputrewrite(v,d){	 
			if (v==d) {
				return "";
			}else if(v==""){
				return d;
			}
		}

		function echeck(str) {

							var at="@"
							var dot="."
							var lat=str.indexOf(at)
							var lstr=str.length
							var ldot=str.indexOf(dot)
							if (str.indexOf(at)==-1){
							   alert("Invalid E-mail")
							   return false
							}

							if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
							   alert("Invalid E-mail")
							   return false
							}

							if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
							    alert("Invalid E-mail")
							    return false
							}

							 if (str.indexOf(at,(lat+1))!=-1){
							    alert("Invalid E-mail")
							    return false
							 }

							 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
							    alert("Invalid E-mail")
							    return false
							 }

							 if (str.indexOf(dot,(lat+2))==-1){
							    alert("Invalid E-mail")
							    return false
							 }

							 if (str.indexOf(" ")!=-1){
							    alert("Invalid E-mail")
							    return false
							 }

					 		 return true					
						}


// 


function video(_o){
	
	
	var w = 480;//$(this).children('img').attr('fullwidth');
	var h = 320+20;//$(this).children('img').attr('fullheight');
	
	var displaydiv = _o.parents('div.exhibit').find('div.media div.mediadisplay').eq(0);
	var src = _o.attr('href');
	displaydiv.html('<div class="flash"/></div>');		
	

	
	displaydiv.children('div.flash').flash(
					{ src: '/_swf/mediaplayer.swf', height: w, width: h, flashvars: { 
						    image: _o.attr('alt'),
								frontcolor:'0x000000',
								backcolor:'0x0000ff',
								screencolor:'0x000000',
								
						file: src, autostart:'auto',usefullscreen:'false',allowfullscreen:'true',showdigits:'false',showicons:'true', shownavigation:'true', bgcolor:'#000000',showdownload:'false', width:w, height:h} },
					{ version: 9},
					function(htmlOptions) {
					        var $this = $(this);
					        htmlOptions.src = '/_swf/mediaplayer.swf';
					        htmlOptions.width = w;
					        htmlOptions.height = h;
					        $this.addClass('flash-replaced').prepend($.fn.flash.transform(htmlOptions));
					 
		});


		return false;
	

		
		
		

		}



						function hasCSS(){
							$('body').append($(document.createElement('div')).attr('id','css_test').css({width:'1px',height:'1px',display:'none'}));
							var _v=($('#css_test').width()!=1)?false:true;
							$('#css_test').remove();return _v;
						};


						function parseUrl(){								
							launchWindow( $('.window#win_'+_urlid) , "1" );
						}
