


// Updated January 16, 2011 - added isExpanded to resetCellSize function - required for other features ie. hover captions 
// Updated January 8, 2011 - [mds.com]
// Last updated September 11, 2009 6:30pm - AB 
//
/* ------------		Row Constructor  (See below for other GALLERY SCRIPTS) 	-------------*/

var ids_strng = "";
var br_name = ""; //browserid

//Initial Setup (other than below)
$(document).ready(function() {
	//setup hilighting for pop down menu on thumbnails
	$(".tbpopdneditor").bind('mouseenter mouseleave' ,function() {
		$(this).toggleClass("hilight_tb_p");
	});

	
	
	
	
	$(".imagebrowser").each(function() {
		if (! $(this).data("loaded") ) {
			var qrystring = $(this).attr("data-params");
			var qrystring2 = $(this).attr("data-params2");
			br_name = $(this).attr("id");
			
			$(this).load('galleryfiles/forms/image_browser_form.php',qrystring, function(response,status,xhr) {
				$(this).data('loaded',true);
				var ccid = getURLParameter("&cid");

				var ids_to_hide = [];
				$("#browser0_selectclick").bind("click",function() {
					var ids_to_hide = qrystring2.split(":");
					ids_strng = qrystring2.replace(/:/gi,",");
					$(ids_to_hide[0]).before("<div id='"+br_name+"_spawn' class='browserspawn'><img src='../galleryfiles/icons/load.gif'/></div>");				
					$(ids_strng).slideUp();
					$("#"+br_name+"_spawn").slideDown(800);					

					//load gallery file 
					var browserloadparams = "cid="+ccid+"&m=imgtargimg_sub_fld_name&l="+br_name+qrystring;
					$("#"+br_name+"_spawn").load('galleryfiles/image_browser.php',browserloadparams);
//					$("#"+br_name+"_spawn").load('galleryfiles/gallerymodules/load_thumbnails.php',browserloadparams );


					//WHEN Done Loading gallery browser file
					$("#"+br_name+"_spawn").promise().done(function() {
						//scroll to top of browser
						jqScroll (br_name+"_spawn"); //no # - assumes it is an ID						
					}); //close when done loading gallery browser
				});
			}); //"callback=?&test=asdf&kk=asdf"); //$(this).attr("data-params") 
		}
	});
});






function getURLParameter(name) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]);
}






////////////////////////////////////////

var gr = new Array();

addEvent(window,'load',loadgallery);

function loadgallery(e) {
	window.name = 'mdsgallery';
}


//// TIMEOUT & FADE FUNCTIONS
var timeoutID = [];
function fade_hide(elid,timeoutIDref,speed_var,wait) {
	//jquery syntax
	timeoutID[timeoutIDref] = setTimeout("$('"+elid+"').hide('"+speed_var+"')",wait);
}

function fade_hide_now(elid,timeoutIDref,speed_var) {
	//jquery syntax 
	clearTimeout(timeoutID[timeoutIDref]);
	if (speed_var == "insant") {
		$(elid).hide();
	} else {
		$(elid).hide(speed_var);
	}
}


///////	ALLOW SORT IMAGE TBs IN GALLERY 

var aasort_ser;
var aasort_tA;
var draggedimg;

$(document).ready(function() { 
	//enable sort feature for gallery
	$(".sortablelist").sortable({
		items: 'li', opacity: .8, placeholder: 'ui-state-highlight', tolerance: 'intersect', handle: '.handle', forceHelperSize: true, tolerance: 'pointer', containment: "#thumbs", scrollSpeed: 50, 
		start: function(event, ui) {
			allow_hover_divs = false;
		}, 
		deactivate: function(event, ui) {
			allow_hover_divs = true;		
			draggedimg = $(".sortablelist").sortable("option","helper");
			//allpics
			aasort_serial = $(".sortablelist").sortable("serialize");
			aasort_tA = $(".sortablelist").sortable("toArray");
			followLink('../galleryfiles/g_jq_row_update.php?'+aasort_serial+ab_args+'&new_image_sorting=y','thumbs_updates');
			//alert(_gebi(this).id);
		}
	});

/*
	$(".dragframe").draggable({ stack: ".dragframe", containment: $("#thumbs"), cursor: "crosshair" });
	$(".dragframe").droppable({
      drop: function() { alert('dropped'); }
    });

*/
})


var allow_hover_divs = true;
//////// HOVER DIVS FOR GALLERY CAPTIONS 
$(document).ready(function() {
	$(".hoverdivsource").mouseenter(function() {
		if (allow_hover_divs) {
			var elid = $(this).attr("id");
			clearTimeout(timeoutID[elid]);
			$("#" + elid + " .allhoverdivs").show("fast");
		}
	});
});

$(document).ready(function() {
	$(".hoverdivsource").mouseleave(function() {
		var elid = $(this).attr("id");
		fade_hide("#" + elid + " .allhoverdivs",elid,"fast",400); //elid, timeoutIDref, speed, delay 
	});
});

//////////////////////////////////////

//Scroll
function jqScroll (toElID,milli) {
	if (!milli) { milli = 1500; }
	$('html, body').animate({
	    scrollTop: $("#"+toElID).offset().top
	}, milli);
}

/////////////////////////////////////
function MakeGalleryThumbRows(numRows)
{
//	alert("make constructor"+numRows);
	for (var i = 0; i < numRows; i++) {
		gr[i] = new rowConstructor(i);
	}
}



function rowConstructor(id)
{
	/* define properties */
	this.ID            = 'thumbrow'+id; // the Current row ID
	this.timerID       = -1; // the Current Menu's Delay timer
	this.isExpanded = false; // the Current Menu's Display Status
	this.numCells	= 0;
	this.name		= name;
	
	this.ii	= new Array(); //ids for each table cell within
	this.w		= new Array(); //std width for each table cell within
	this.h		= new Array(); //std ht for each table cell within
	this.path		= new Array();
	this.tbpath	= new Array();
	this.bigw		= new Array();
	this.bigh		= new Array();
	
	/* define methods */
	this.updaterowcells = update_rowcells;
	this.test		= testalertii;
	this.insertcell	= insert_cell;
	this.testreturnall	= returnall;

	return this;
}

function returnall() {

	var xx = 'ID ' + this.ID + ' \n timerID: ' + this.timerID + ' \n isExpanded: ' + this.isExpanded + ' \n numCells: ' + this.numCells + ' \n name:' +
		this.name + ' \n ii: (' + this.ii.join(',') + ') \n w: (' +
		this.w.join(',') + ') \n h: (' +
		this.h.join(',') + ') \n bigw: (' +
		this.bigw.join(',') + ') \n bigh: (' +
		this.bigh.join(',') + ') \n path: (' +
		this.path.join(',') + ') \n tbpath: (' +
		this.tbpath.join(',') + ' \n';
	alert(xx);
}

function update_rowcells(ids,w,h,wbig,hbig,truew,trueh,paths,tbpaths,maxrowht) 
{
	//ARRAYS
	this.ii 	= ids; 
	this.w			= w; //std width for each table cell within
	this.h			= h; //std ht for each table cell within
	this.bigw		= wbig;
	this.bigh		= hbig;
	this.path		= paths;
	this.tbpath		= tbpaths;
	this.numCells	= ids.length;
	
	this.truew		= truew;
	this.trueh		= trueh;

	//SINGLE VARIABLES
	this.maxrowht	= maxrowht;
}

function insert_cell (row,ids,w,h,wbig,hbig,path,tbpath) {
	this.ii.push(ids);
	this.w.push(w);
	this.h.push(h);
	this.bigw.push(wbig);
	this.bigh.push(hbig);
	this.path.push(path);
	this.tbpath.push(tbpath);
	
	this.numCells++;
}

function testalertii() {
	var strng = '';
	for (i=0; i < this.numCells; i++) {
		strng = strng + i + '. (' + this.ii[i] + ')    \n';
	}
	alert(strng);
}


/* //--------------------------------------------------------------------------------------// JavaScript Document */

/*

											if (gr[r].ii[i] > 0) {
												var thumbht = ((gr[r].h[i]/gr[r].w[i])*(gr[r].w[i]-smallwdiff));
												var tcellname = \"t_cell\"+i+gr[r].ii[i];
												_gebi(tcellname).setAttribute(\"style\",\"height: ".($rowht)."px; width: "
													.($cellw-$small_w_diff)."px; left: \"+leftpos+\"px; ".$tcell_style."\");
													
												var imageframename = \"image_frame\"+gr[r].ii[i];
												
												_gebi(imageframename).setAttribute(\"style\",\"width: \"+gr[r].w[i]+framemargin-smallwdiff+\"px; height: \"+(thumbht+framemargin)+\"px; ".$imageframesstyle."  \");
												
												var thumbname = \"thumb\"+gr[r].ii[i];
												_gebi(thumbname).setAttribute(\"style\",\"height: \"+thumbht+\"px; width: \"+(gr[r].w[i]-smallwdiff)+\"px; ".$imagestyle."\");	
											} /* END make sure gr[r].ii[i] is greater than zero. We inserted a blank to make an array > 1 
*/	


function setCellSize(r , i , smallwdiff , framemargin , leftpos , cellw , maxrowht , tcellstyle , imageframestyle , imagestyle) {
	if (gr[r].ii[i] > 0) {
		var thumbht = ((gr[r].h[i]/gr[r].w[i])*(gr[r].w[i]-smallwdiff));
//		var tcellname = "tcell"+i+"_"+gr[r].ii[i];
		var tcellname = "tcell_"+gr[r].ii[i];		
		
//		_gebi(tcellname).setAttribute("style","height: "+maxrowht+"px; width: "+(cellw-smallwdiff)+"px; left: "+leftpos+"px; " + tcellstyle + " ");
//		var currTh = _gebi(tcellname).style.height;
//		var currTw = _gebi(tcellname).style.width;
		setAstyle(_gebi(tcellname),"height: "+maxrowht+"px; width: "+(cellw-smallwdiff)+"px; left: "+leftpos+"px; " + tcellstyle + " ");
//		setAstyle(_gebi(tcellname),"left: "+leftpos+"px; " + tcellstyle + " ");		
//		fadeSize(tcellname,1,10,(cellw-smallwdiff),maxrowht,parseInt(currTw),parseInt(currTh));
				
		var imageframename = "image_frame"+gr[r].ii[i];
		
/* 		_gebi(imageframename).setAttribute("style","width: "+gr[r].w[i]+framemargin-smallwdiff+"px; height: "+(thumbht+framemargin)+"px; "+ imageframestyle +"  "); */

		setAstyle(_gebi(imageframename),"width: "+gr[r].w[i]+framemargin-smallwdiff+"px; height: "+(thumbht+framemargin)+"px; "+ imageframestyle +"  ");
		
		var thumbname = "thumb"+gr[r].ii[i];
		setAstyle(_gebi(thumbname),"height: "+thumbht+"px; width: "+(gr[r].w[i]-smallwdiff)+"px; "+ imagestyle +" ");	
/*		_gebi(thumbname).setAttribute('style',"height: "+thumbht+"px; width: "+(gr[r].w[i]-smallwdiff)+"px; "+ imagestyle +" ");			 */
	}
	
	/* END make sure gr[r].ii[i] is greater than zero. We inserted a blank to make an array > 1 */	
}

/*function resetCellSize(str) {
	alert(str);*/
function resetCellSize(r , smallwdiff , framemargin , leftpos , cellw , maxrowht , tcellstyle , imageframestyle , imagestyle) {
	for (i=0; i < gr[r].numCells; i++) {
		setCellSize(r , i , smallwdiff , framemargin , (leftpos*i) , cellw , maxrowht , tcellstyle , imageframestyle , imagestyle);
	}
	gr[r].isExpanded = false;
}


var imageframestyle,imagestyle,tcellstyle;

function ss(r,smallwdiff,framemargin,partleftpos,cellw,mrowht) {
//	gr[r].isExpanded = false;
	if (document.getElementsByName('shift'+r)) {
		multipleSetByName('shift'+r,'class','show');
	}
	resetCellSize(r , smallwdiff , framemargin , partleftpos , cellw , mrowht , tcellstyle , imageframestyle , imagestyle);
	
//	fadeOneSize ("thumbrow"+r,1,10,(mrowht+2),parseInt(_gebi('thumbrow'+r).style.height),"height");
	
	_gebi('thumbrow'+r).style.height = 	(mrowht+2)+'px';
	rem_el("toolbox");
	//gr[r].isExpanded = false;
}

function getStyleObjectz(objectId) {
	if(document.getElementById && document.getElementById(objectId)) {
		return document.getElementById(objectId).style;
	} else if (document.all && document.all(objectId)) {
		return document.all(objectId).style;
	} else if (document.layers && document.layers[objectId]) {
		return getObjNN4(document,objectId);
	} else {
		return false;
	}
} 

/* ------------		GALLERY ZOOM FADE SIZE 	--------------------- */

function setStyleFromArrayB(objt,attr_arr,prop_arr) {
	
	var el = _gebi(objt);
	for (var css_counter = 0; css_counter < attr_arr.length; css_counter++) {
//	alert("el.style."+attr_arr[css_counter] +" = " + prop_arr[css_counter]+ "   ");
		el.style.attr_arr[css_counter] = prop_arr[css_counter];
	
	}
}

function setStyleFromArray(objt,attr_arr,prop_arr) {
	
	var el = _gebi(objt);
	var css_counter;
	for (css_counter=0; css_counter<attr_arr.length; css_counter++) {
		var attr_type;
		attr_type = attr_arr[css_counter];
		el.attr_type = prop_arr[css_counter];
//		alert(style.attr_arr[i] +"  " + prop_arr[i]);
	}
}

function fadeSize(el,waittime,increm,endW,endH,orW,orH) {
	//desiredPw/h are desired % change for each
	var desiredP = 1.1;

	var elOb = _gebi(el);
	

//	var endW = Math.round(orW*desiredP);
//	var endH = Math.round(orH*desiredP);
	
	var ww = parseInt(elOb.style.width);
	var hh = parseInt(elOb.style.height);
	
	var plusOrMinus = ((endW-orW) > 1) ? 1 : -1;
	
	var SizeIncrW = plusOrMinus * Math.ceil((orW/orH)*increm);
	var SizeIncrH = plusOrMinus * Math.ceil(increm); //h/w = HH/WW
	
	
	
	if ((ww == endW) || (hh == endH)) {
		//if we have reached the right size, end the loop.
		return true;
	}
	
	var newW = ww + SizeIncrW;
	var newH = hh + SizeIncrH;
	
	//make sure we don't exceed our target before we set the target 
	if (desiredP > 1) {
		//INCREASING IN SIZE 
		if ((newW >= endW) || (newH >= endH)) {
			if ((newW >= endW) && ((endH-newH) > SizeIncrH)) {
				newW = endW;
				elOb.style.width = newW+"px";
				fadeOneSize(el,waittime,increm,endH,hh,"height");
				return true;
			} else if ((newH >= endH) && ((endW-newW) > SizeIncrW)) {
				newH = endH;
				elOb.style.height = newH+"px";
				fadeOneSize(el,waittime,increm,endW,ww,"width");
				return true;
			} else {
				newW = endW;
				newH = endH;
				elOb.style.width = newW+"px";
				elOb.style.height = newH+"px";				
				setTimeout("fadeSize('"+el+"',"+waittime+","+increm+","+endW+","+endH+","+orW+","+orH+")");
			}
		} else {
			//set element size 
			elOb.style.width = newW+"px";
			elOb.style.height = newH+"px";
			
			//call loop
			setTimeout("fadeSize('"+el+"',"+waittime+","+increm+","+endW+","+endH+","+orW+","+orH+")");
		
		}
	} else {
		if ((newW <= endW) || (newH <= endH)) {
			newW = endW;
			newH = endH;
		} else {
			//set element size 
			elOb.style.width = newW+"px";
			elOb.style.height = newH+"px";
			
			//call loop
			setTimeout("fadeSize('"+el+"',"+waittime+","+increm+","+endW+","+endH+","+orW+","+orH+")");
		
		}
	}
	
}

function fadeOneSize (el,waittime,increm,endSz,orSz,HorW) {
	var elOb = _gebi(el);
	
	var desiredP = 1.2;

	//var endSz = Math.round(orSz*desiredP);
	
	if (HorW == "height") {
		var currSz = parseInt(elOb.style.height);
	} else {
		var currSz = parseInt(elOb.style.width);	
	}
	
	var plusOrMinus = ((endSz-orSz) > 1) ? 1 : -1;
	
	var SizeIncr = plusOrMinus * Math.ceil(increm);

	if (currSz == endSz) {
		//if we have reached the right size, end the loop.
		return true;
	}
	
	var newSz = currSz + SizeIncr;
	
	//make sure we don't exceed our target before we set the target 
	if (desiredP > 1) {
		if (newSz >= endSz) {
			newSz = endSz;			
		}
	} else {
		if (newSz <= endSz) {
			newSz = endSz;
		}
	}
	
	//set element size 
	if (HorW == "height") {
		elOb.style.height = newSz+"px";
	} else {
		elOb.style.width = newSz+"px";
	}
	
	//call loop
	setTimeout("fadeOneSize('"+el+"',"+waittime+","+increm+","+endSz+","+orSz+",'"+HorW+"')");
	
}


/* ------------		GALLERY BROWSER 	--------------------- */


function end_browser() {
	rem_el("blankbg"); 
	rem_el("browser_underlay");
	return;
}

function end_browser_and_scroll(scrolltoID) {
	rem_el("blankbg"); 
	rem_el("browser_underlay");
	if (_gebi(scrolltoID)) {
		ScrollToElement(scrolltoID);
	}
	return;
}


function new_upload_form(formnum,targetdiv) {
	//create new upload form to replace form on submit 
	//make_el_dom("div","show","",targetdiv,"upformdiv"+formnum);
	
	var upformd = document.createElement("div");
	_gebi(targetdiv).appendChild(upformd);
	upformd.id = "upformdiv"+formnum+'';
	upformd.style.border ='1px solid green';
	
	make_el_dom("form","","","upformdiv"+formnum,"upform"+formnum);

	formEl = _gebi("upform"+formnum);
	formEl.style.marginLeft = "1em";
	formEl.style.marginRight = "1em";
	formEl.name='uploadimages'+formnum;
	formEl.enctype = 'multipart/form-data';

	make_el_dom("p","para_medtxt"," ","upform"+formnum,"formp"+formnum);

	make_el_dom("div","para_medtxt graywriting","","upform"+formnum,"photo_browse"+formnum);
	
	
	var photo_browse = _gebi('photo_browse'+formnum);
	photo_browse.style.border = "1px solid red";
	photo_browse.appendChild(document.createTextNode('Photo: '));
	
	var fileinp = document.createElement("input");
	fileinp.id = "file_browser"+formnum;
	fileinp.name = " photo"+formnum+"_filename[]";
	fileinp.type = "file";
	fileinp.onchange = function () {
						var formnum = _gebi('formnumber').value;
						var whichcat = get_radio_value('which_catj');
						var ind = _gebi('selcid').selectedIndex;
						var selectedcid = _gebi('selcid').options[ind].value;
						var newformnum = (parseInt(formnum) + 1);
						new_upload_form(newformnum,'singleuploadf');
	fileUpload(this.form,'../galleryfiles/upload_image.php?formnumber='+formnum+'&which_cat='+whichcat+'&selectedcid='+selectedcid,'upload'+formnum);
						_gebi('formnumber').value = newformnum;
						rem_el('photo_browse'+formnum);
	}
	_gebi('photo_browse'+formnum).appendChild(fileinp);
	
	make_el_dom("div","para_medtxt"," ","upform"+formnum,"upload"+formnum);
	_gebi('upload'+formnum).style.margin = "1em";

}

