window.element_selected = 'default'; 
window.default_cat = 5;
window.cat_selected = window.default_cat;
window.categories_selected_elements = [];
window.snap = 200;
window.category_meta = []

window.image_info_height = 22;//image_info
window.location_image_loc='http://static.primr.net/tmp/';
window.location_image_proc='http://static.primr.net/media/asset/img.php?';

window.preloadImages = [];

window.category_loaded_state = null;
window.loading_cat = false;




window.h_column_width = 160;
window.adj_height = 0;

window.display_mode = 'standard';

window.thumbnails_toggle = 0;
window.slideshow_toggle = 0;
 
function debug(d_string, callfunction){
	///return;
	var jfield = $('#debug');
	if((callfunction)&&(callfunction=='clean')){
		jfield.html("");
	}
	jfield.prepend('<div>'+d_string+'</div>');
	return true;
}






function xmlhttpPostToTarget(strURL, strVALUE, strTARGET ) {
	window.ajax_req_time = new Date();
    var xmlHttpReq = false;
    var self = this;

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

    self.xmlHttpReq.open('POST', strURL+strVALUE, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText, strTARGET);
        }
    }





    self.xmlHttpReq.send(strVALUE);

}



function updatepage(returnstr, page_target_str){
	

	var target_div = $('div[id="'+page_target_str+'"]');
	///debug(page_target_str+" "+target_div.html());
	target_div.html(returnstr);
	var time_now = new Date();
	
	
	debug("AJAX:" + (time_now.getTime()-window.ajax_req_time.getTime()) + "ms."+window.ajax_url,'clean');	

	if (window.loading_cat == true) { 
		if (window.category_loaded_state == null) {
			///fired on initial load only
			window.category_loaded_state = true;
			category_loaded('first_run');
		}else{
			category_loaded('ajax');
		}
	}
	
	///draw_page(1); 
	return false;
	
}


//IMAGING//
//IMAGING//
//IMAGING//

function preloadImg(image, imgid){
	
	var counter = window.preloadImages.length;
	
	window.preloadImages[counter] = new Image();
	window.preloadImages[counter].onerror = function() { 
		debug("Image file '" +image+ "' could not be loaded!"); 
		return false;
	}
	
	window.preloadImages[counter].setAttribute('class','image_part');
	window.preloadImages[counter].setAttribute('id',(imgid+'_image_part'));
	
	window.preloadImages[counter].onload = function() { 
		debug("Image file '" +image+ "' was loaded!");
		window.preloadImages[counter].setAttribute('loaded','1');
		
		if(window.preloadImages[counter].getAttribute('urgent')==1){
			window.preloadImages[counter].setAttribute('urgent',0);
			element_loaded(window.preloadImages[counter]);
		}
		
	} 
	
	window.preloadImages[counter].src = image;
	return window.preloadImages[counter];
}



function load_element(idnumber, sobject){
	$('#loadIcon').css('visibility','visible');
	var ref = 0;
	var fge = window.categories_selected_elements[window.cat_selected];
	
	if(idnumber=="next"){ 
		ref = (fge)+1;
		if (ref >= window.category_meta[window.cat_selected].length) {ref = 0;};
		idnumber = window.category_meta[window.cat_selected][ref];
		window.categories_selected_elements[window.cat_selected] = ref;
	}
	
	if(idnumber=="previous"){
		ref = (fge)-1;
		if (ref == -1) {
			ref = window.category_meta[window.cat_selected].length-1;
		}
		debug(ref);
		idnumber = window.category_meta[window.cat_selected][ref];
		window.categories_selected_elements[window.cat_selected] = ref;
	}

	var cg = get_array_index(idnumber*1); 
	if(cg!=-1){
		window.categories_selected_elements[window.cat_selected] = cg;
	}
	
	window.element_selected = idnumber;
	
	///load the element to a JQery object;
	var element_source_filename = $('div[id="element_'+idnumber+'_file"]');
	var req_w = Math.floor(window.available_image_w/window.snap)*window.snap;
	var req_h = Math.floor(window.available_image_h/window.snap)*window.snap;

	///var loadfile = window.location_image_proc+req_w+":"+req_h+"/"+element_source_filename.html();
	var loadfile = window.location_image_loc+req_w+"px/"+element_source_filename.html();
    
    var loading_element = preloadImg(loadfile, idnumber);
	loading_element.setAttribute('urgent',1);

}






function element_loaded(img_obj){
	
	$('#image_tag').html(img_obj);
	$('#image_tag').width('auto');
	$('#image_tag').height('auto');
		
	ctw = $('#image_tag').width();
	cth = $('#image_tag').height();
	
	$('#image_tag').attr('og_width',ctw);
	$('#image_tag').attr('og_height',cth);

	if(window.loading_cat == true){
		adj_animate('toggle_thumbnails');
		window.loading_cat = false;
	}else{
		draw_page();
	}
	
	$('#image_tag').css('display','none');
	$('#image_tag').fadeIn();
	debug('image info: w'+ctw+'px h'+cth+'px.');
	$('#loadIcon').css('visibility','hidden');
}


 
 




//END IMAGING//
//END IMAGING//
//END IMAGING//



function get_array_index(item){
	ct = window.category_meta[window.cat_selected];
	cg = item*1;
	var haspos = ct.indexOf(cg);
	return haspos;
}


function load_category(tcategory){
	window.loading_cat = true;
	local_location_Handle = '';
	nurl = '/cat/thumbs/'+tcategory;
	window.cat_selected = tcategory;
	//var listing = $('div[id="list_'+window.cat_selected+'"]');
	//listing.addClass("shelect");
		
	xmlhttpPostToTarget(local_location_Handle, nurl, 'category_thumbnails' );
	///$('#category_thumbnails').fadeOut();
}



function category_loaded(type){
	debug("category_loaded("+type+") ["+window.cat_selected+"] IMAGE:"+window.element_selected);
	var que_preload = null;
	
	///first run for category FIRST LOAD ONLY
	//process elements in set to arrays.
	
	if(!window.category_meta[window.cat_selected]){
		
		window.category_meta[window.cat_selected] = [];
		var thset = $('#context_element_set');
		strp = thset.html();
		steppy = strp.substring(1,strp.length-1);
		steppy = steppy.replace(/^\s*/,"");
		var id_array = steppy.split(',');
		window.category_meta[window.cat_selected] = id_array;
		for (var d = 0; d < id_array.length; d++) {
			id_array[d]*=1;
		}
		///sets this category's array position to default zero on first load.
		window.categories_selected_elements[window.cat_selected] = 0;
		
		///first_run!!!
		
		if(window.display_mode != 'mini'){
			que_preload = 1;
		}
			
		
		
	}else{
		
		
		var df = window.categories_selected_elements[window.cat_selected];
		if(df){
			var fg = window.category_meta[window.cat_selected][df];
			window.element_selected = fg;
		}
	
	
	
	}
	
	
	
	
	
	if(window.element_selected=='default'){
		window.element_selected = window.category_meta[window.cat_selected][0];
		debug("have default selection:("+window.element_selected+")");
	}
	
	
	cg = get_array_index(window.element_selected*1);
	
	if(cg!=-1){
		window.categories_selected_elements[window.cat_selected] = cg;
	}else{
		window.element_selected = window.category_meta[window.cat_selected][0];
	}
	
	
	
	
	debug(window.categories_selected_elements);
	
	cte = window.element_selected;
	
	var target_e = $('a[id="element_'+cte+'"]');
	//load selection or default main image:
	d = target_e.click();
	debug(d+" "+target_e.attr('id'));
	////que_preload = null;
	
	if (que_preload) {
		window.setTimeout("queue_preload()",5000);
	}
	
}

function queue_preload(){

	var req_w = Math.floor(window.available_image_w/window.snap)*window.snap;
	var req_h = Math.floor(window.available_image_h/window.snap)*window.snap;
	var set = window.category_meta[window.cat_selected];
	
	for(var c=0;c<set.length;c++){
		var target_node = set[c];
		var element_source_filename = $('div[id="element_'+target_node+'_file"]');
        ///var loadfile = window.location_image_proc+req_w+":"+req_h+"/"+element_source_filename.html();
		var loadfile = window.location_image_loc+req_w+"px/"+element_source_filename.html();
		var loading_element = preloadImg(loadfile, target_node);
	}
	
}


function load_new_page(tnone){

	window.cat_selected = window.default_cat;
	window.element_selected = 'default';
			
	if (window.location.toString().indexOf('#') !== -1) {
		
		
		var tre = window.location.toString().split('#');
		if (tre[1]) {
			var est = tre[1].split('/');
			if (est.length != null) {
				window.cat_selected = est[0];
				if (est[1]) {
					window.element_selected = est[1];
				}
			}
			else {
				window.cat_selected = parseInt(est);
				window.element_selected = 'default';
			}
		//}else{
			//window.cat_selected = window.default_cat;
			//window.element_selected = 'default';
		}
		
		load_category(window.cat_selected);
	}else{
		if (window.location.toString().indexOf('contact') === -1) {
			load_category(window.cat_selected);
		}
	}
	
	
	

	

} 



function toggle_thumbnails(){
	cfg = ['off','on','off'];
	window.thumbnails_toggle = Math.abs(window.thumbnails_toggle-1);
	$('#thumbnails_on').html(' '+cfg[window.thumbnails_toggle]);
	
	adj_animate('toggle_thumbnails');
}



function adj_animate(call_funct){
	
	var offset = $('#category_thumbnails').height()*window.thumbnails_toggle;
	
	
	var ost = (window.present_h-offset)-window.image_info_height;
	var og_w = $('#image_tag').attr('og_width');
	var og_h = $('#image_tag').attr('og_height'); 
			
	window.delta_to_screen = (ost / window.innerHeight);		
			
	if (call_funct == 'toggle_thumbnails') {
		var dex = 0;
		var dey = 0;
		delta_perc = 1;
		var display_ratio = 1;
		
		if (window.thumbnails_toggle == 1) {
			
			delta_perc = (ost / window.innerHeight);
			
			$('#image_bounds').attr('scaled', delta_perc);
			
			
			
			
			
			
			
		}else{
			delta_perc = 1 / ($('#image_bounds').attr('scaled'));
			$('#image_bounds').attr('scaled', 1);

			dex = og_w;//*display_ratio;
			dey = og_h;///*display_ratio;
		}
		
	}

	var delta_scale_w = Math.round(delta_perc * ($('#image_tag').width()));
	var delta_scale_h = Math.round(delta_perc * ($('#image_tag').height()));
	var lext = $('img[id=' + (window.element_selected) + '_image_part]');
	
	if(dex!=0){delta_scale_w=dex;};
	if(dey!=0){delta_scale_h=dey;};
	
	image_ost_d = ((ost/2)-(delta_scale_h/2));
	
	$('#image_tag').animate({
		top:image_ost_d,
		width: delta_scale_w,
		height: delta_scale_h
	}, 500, function(){
		window.study_window();
	});
	
	
	lext.animate({
		width: delta_scale_w,
		height: delta_scale_h
	}, 500, function(){
		window.study_window();
	});
	

	$('#image_bounds').animate({
		height : ost
	}, 500, function(){
		window.study_window();
	});

}








function study_window(){
	return true;
}


function jq_doc_ready(){
	
	window.image_info_height = $('#image_info').height();
	draw_page(1);
	var endDate = new Date();
	debug("load:" + (endDate.getTime() - loadDate.getTime()) + "ms.");	
	load_new_page(1);
	
	$('#image_bounds').attr('scaled',1);
	
	$('a').hover(function () {
      $(this).addClass("shilite");
    }, function () {
      $(this).removeClass("shilite");
    });
	
		
	$('.cat_list_item').click(function () {
      $(this).addClass("shelect");
    }, function () {
      $(this).removeClass("shelect");
    });
	
}


$(document).ready(function() {
	jq_doc_ready();
});



function draw_image(){
	ctop = ($('#image_bounds').height()/2)-($('#image_tag').height()/2);
	$('#image_tag').css('top',(ctop));
	last_update();
}

function toggle_slideshow(){
	window.slideshow_toggle
	cfg = ['off','on','off'];
	window.slideshow_toggle = Math.abs(window.slideshow_toggle-1);
	$('#slideshow_on').html(' '+cfg[window.slideshow_toggle]);
}


function last_update(){
	var fdg = window.category_meta[window.cat_selected];
	if (fdg) {
		var sindex = window.categories_selected_elements[window.cat_selected];
		var pnxt = sindex + 1;
		var pprv = sindex - 1;
		if (pnxt >= fdg.length) {pnxt = 0;};
		if (pprv < 1) {pprv = fdg.length - 1;};
		$('#nextimage').attr('href', ('/#' + window.cat_selected + '/' + (fdg[pnxt])));
		$('#previousimage').attr('href', ('/#' + window.cat_selected + '/' + (fdg[pprv])));
	}
	
	
	var missile = $('.cat_list_item');
	for(var ps=0;ps<missile.length;ps++){
		var tc = $(missile[ps]);
		if (tc.attr('id') == 'list_'+window.cat_selected) {
			tc.addClass("shelect")
		}else{
			tc.removeClass("shelect");
		}
	} 
	$('#loadIcon').css('visibility','hidden');
	
	has_info = $('img[id="thumbnail_'+window.element_selected+'"]').attr('label');
	if (has_info) {
		$('#image_info').html(has_info);
	}else{
		$('#image_info').html("");
	}
}









function draw_page(evt){

	
	
	
	window.present_w = window.innerWidth;
	window.present_h = window.innerHeight;
	
	var ost = $('#category_thumbnails').height()*window.thumbnails_toggle;
	var th_hgt = (window.present_h-(ost))-(window.image_info_height);

	if (window.present_w < 600) {
		window.display_mode = 'mini';
		/*
		$('#category_thumbnails').width('auto');
		$('#category_thumbnails').css('left', 0);
		$('#category_thumbnails').css('top', th_hgt);
		
		window.available_image_w = 400;
		window.available_image_h = 400;
		
		$('#image_bounds').width(200);
		$('#image_bounds').height(300);
		$('#image_bounds').css('left', 0);
		$('#image_bounds').css('top', 0);
		
		$('#category_thumbnails').css('top', $('#image_bounds').height());
		
		$('#image_tag').width(200);
		*/
	}else {
		
		
		
		column_one = window.h_column_width;
		column_two = ((window.present_w) - window.h_column_width);
		
		$('#marka').css('top', 0);
		$('#markb').css('top', 0);
		$('#marka').css('left', column_one);
		$('#markb').css('left', column_two);
		
		var cw = window.present_w - (column_one * 2);
		ch = window.present_h;
		
		$('#markb').html(column_two+" "+cw+" "+ch+" "+$('#image_bounds').attr('scaled')+"%");
		
		$('#context').css('left', column_one);
		$('#context').css('top', 0);
		$('#context').width(cw);
		$('#context').height(window.present_h);
		
		 
		
		$('#markc').css('top',th_hgt);
		
		var og_w = $('#image_tag').attr('og_width');
		var og_h = $('#image_tag').attr('og_height'); 
		///sometimes ost is null
		var lext = $('img[id=' + (window.element_selected) + '_image_part]');
		var display_ratio = th_hgt/og_h;
		///display_ratio*=
		
		if(display_ratio <= 1){
			
				
			$('#image_tag').width((og_w*(display_ratio*1)));
			$('#image_tag').height((og_h*(display_ratio*1)));
			lext.width($('#image_tag').width());
			lext.height($('#image_tag').height());
			
			$('#image_tag').css('top',0);
		}else{
			
		}
		$('#image_tag').width($('#image_tag').width()*window.delta_to_screen);
		$('#image_tag').height($('#image_tag').height()*window.delta_to_screen);
		lext.width($('#image_tag').width());
		lext.height($('#image_tag').height());
		
		
		
		
		
		var cv = (th_hgt/2)-($('#image_tag').height()/2);
		$('#image_tag').css('top',cv); 
		
		
		
		 
		$('#image_bounds').height(th_hgt);
		window.display_percent = display_ratio;
		

		/// $('#image_bounds'). 
		$('#markc').html("["+display_ratio+"]"+window.present_h+" "+ost);
		
		
		
		$('#markd').css('top',(th_hgt/2));
		
		window.available_image_w = cw;

	}
	
	
	
	window.available_image_h = window.present_h;
	 
	$('#nav').css('top',(window.present_h/2)-100);
	 
	
	
	
	
	
	
	last_update();
	return true; 
}









function handle_th(item){
	var th = ($(item.parentNode.parentNode).height()/2)-($(item).height()/2);
	$(item).css('top',th);
	$(item).fadeIn();
}
 
function toggle_debug(){
	$('#debug').css('left',window.h_column_width);
	$('#debug').slideToggle();
}

function updater(){
	if (window.slideshow_toggle) {
		load_element('next',this);
	}
	window.setTimeout("updater()", 4000);
}
 
 function relay_event(evt){
	var ttarget = evt.target;  
	if((ttarget.nodeName!='A')&&(ttarget.nodeName!='IMG')){
		var cd = window.innerWidth;
		if(evt.pageX>(cd/2)){
			$('#nextimage').click();
		}else{
			$('#previousimage').click();
		}
	}
}




 
 updater();///start queue


