var dd_aHover = false;
var dd_aDragging = false;
var dropZoneZ = 500;
var photoZ = 1000;

var items = 0;
var selection = new Array();

function th_init() {
	thumbs = xGetElementsByClassName('thumbnail');
	for(n=0;n<thumbs.length;n++) {
		thumbs[0].firstChild.id="thumb"+n;
		th_add(thumbs[0].firstChild);
	}
}

function th_add(ele) {
	xEnableDrag(ele,th_dragStart,th_dragDuring,th_dragEnd);
}

function th_dragStart(ele,x,y) {

	if(ele.getAttribute('class') == "thumbnail") {
	
		drag_ele = ele.parentNode.cloneNode(true);
		drag_ele.id = 'thumb_drag';
		drag_ele.setAttribute('class','thumbnail_drag');

		drag_ele = document.body.appendChild(drag_ele);
		drag_ele.style.position='absolute';
		
		xTop(drag_ele,ele.parentNode.offsetTop+ele.offsetTop);
		xLeft(drag_ele,ele.parentNode.offsetLeft+ele.offsetLeft);

		xdOnMouseup(ele);

		xEnableDrag(drag_ele.firstChild,th_dragStart,th_dragDuring,th_dragEnd);
		drag_ele.firstChild.target=drag_ele.firstChild;
		drag_ele.firstChild.type='mousedown';
		xdOnMousedown(drag_ele.firstChild);

	} else {
		dd_aDragging = ele;
		ele.startX = xLeft(ele);
		ele.startY = xTop(ele);
		ele.totalMX = 0;
		ele.totalMY = 0;
	}
}

function th_dragDuring(ele, mdx, mdy)
{
	xMoveTo(ele.parentNode, xLeft(ele.parentNode) + mdx, xTop(ele.parentNode) + mdy);
	ele.totalMX += mdx;
	ele.totalMY += mdy;
}

function th_dragEnd(ele, mx, my)
{
	if(dd_aHover && ele.getAttribute('class')=="thumbnail") {
		dd_aHover.setAttribute('class',dd_aHover.getAttribute('dd_normal_class'));
		dd_aHover.setAttribute('className',dd_aHover.getAttribute('dd_normal_class'));

		if(dd_aHover.onDrop) {
			dd_aHover.onDrop(ele,dd_aHover);

		}
		dd_aHover=false;

	} else if(ele.getAttribute('class')!="thumbnail") {
		if(dd_aHover.onDrop) {
			dd_aHover.onDrop(ele,dd_aHover);
		} else if(ele.onDrop) {
			ele.onDrop(ele,dd_aHover);
		}
	}

	dd_aHover = "";
	dd_aDragging="";
	snap = ele.getAttribute('snap');
	if(snap==1) {
		xSlideTo(ele, ele.startX, ele.startY, 100);
	}
}

function dd_dropZone(pe,ne,w,h,x,y,aclass,nclass,oclass,ondrop,noslider) {

	pe = xGetElementById(pe);

	newzone = xCreateElement('div');

	newzone.id = ne;
	newzone.zType = 1;
	newzone.style.position="relative";

	newzone = pe.appendChild(newzone);

	xWidth(newzone,w);
	xHeight(newzone,h);
	xLeft(newzone,x);
	xTop(newzone,y);
	
	newzone.setAttribute('class',nclass);
	newzone.setAttribute('className',nclass);
	

	if(e = xGetElementById(ne)) {
		e.setAttribute('dd_dropzone',"true");
		e.setAttribute('dd_accepts_class',aclass);
		e.setAttribute('dd_over_class',oclass);
		e.setAttribute('dd_normal_class',nclass);
		
		e.onDrop=ondrop;
		xZIndex(e,dropZoneZ++);
		if(!noslider) {
			dd_addSlider(ne,'');
		}
	}

}

function dd_addSlider(ele,handle) {
	e=xGetElementById(ele);
	
	container = document.createElement('div');
	container.id="slider_"+e.id;
	container.setAttribute('class','slider_container');	
	container.setAttribute('className','slider_container');	
	container.dd_attachedTo = e.id;	
	container.style.position="relative";
	container.style.zIndex=100;
	handle = document.createElement('div');
	handle.id="slider_handle_"+e.id;

	handle.setAttribute('class','slider_handle');	
	handle.setAttribute('className','slider_handle');	
	
	container.appendChild(handle);

	if(!is_ie) {	
		slider_block = document.getElementById('slider_block');
	}
	container = slider_block.appendChild(container);




	eh = xGetElementById('slider_handle_'+e.id);
	xLeft(eh,xWidth(eh.parentNode.id) - xWidth(eh));

	xEnableDrag(eh,dd_sliderDragStart,dd_sliderDragDuring,dd_sliderDragEnd);

	pe = xGetElementById(e.id);
	
}

function dd_sliderDragStart(ele, mx, my)
{
	ele.totalMX = 0;
	ele.totalMY = 0;
}

function dd_sliderDragDuring(ele, mdx, mdy)
{
	e = xGetElementById(ele);
	
	pe = e.parentNode;
	pWidth = xWidth(pe) - xWidth(e);
	if(xLeft(e)+mdx < pWidth && xLeft(e)+mdx >= 0) {
		xMoveTo(e, xLeft(e) + mdx, xTop(e));	
	}

	style = e.style;

	b = style.left.split('px');
					

	x = parseInt(b[0]);
					
	ae = xGetElementById(pe.dd_attachedTo);


	if(photo = ae.firstChild) {

		if(!photo.getAttribute("originalWidth")) {
			photo.setAttribute("originalWidth", xWidth(photo));
			photo.setAttribute("originalHeight",xHeight(photo));
		}
						
		percent = (x * .01);
									
		xWidth(photo,photo.getAttribute("originalWidth") * percent);
		xHeight(photo,photo.getAttribute("originalHeight") * percent);
	}
}

function dd_sliderDragEnd(ele, mx, my)
{
	e=xGetElementById(ele);

	ae = xGetElementById(e.parentNode.dd_attachedTo);
	if(ae.firstChild) {
		recordZone(ae.id);
	}
}

function dd_addDraggable(ele,snap,ondrop) {
	e=xGetElementById(ele);
	e.setAttribute('snap',snap);

	e.onDrop = dd_report;

	xEnableDrag(e,dd_dragStart,dd_dragDuring,dd_dragEnd);
}

function dd_dragStart(ele, mx, my)
{
		drag_ele = ele.cloneNode(true);

	if(ele.getAttribute('class') == "thumbnail" || ele.getAttribute('className') == "thumbnail") {
	
		drag_ele = ele.cloneNode(true);

	
		drag_ele.id = 'dragg_'+ele.id.substr(6);

		if(drag_ele.getAttribute('class')) {
			drag_ele.setAttribute('class','thumbnail-drag');
		} else {
			drag_ele.setAttribute('className','thumbnail-drag');
		}
		drag_ele.style.position="absolute";
		drag_ele = document.body.appendChild(drag_ele);

		xZIndex(drag_ele,500);

		drag_ele.startX = xLeft(ele);
		drag_ele.startY = xTop(ele);

		xLeft(drag_ele,drag_ele.startX);
		xTop(drag_ele,drag_ele.startY);

		xdOnMouseup(ele);

		xEnableDrag(drag_ele,dd_dragStart,dd_dragDuring,dd_dragEnd);
		drag_ele.target=drag_ele;
		drag_ele.type='mousedown';
		xdOnMousedown(drag_ele);
	} else {

		dd_aDragging = ele;
		ele.startX = xLeft(ele);
		ele.startY = xTop(ele);
		ele.totalMX = 0;
		ele.totalMY = 0;

	} 



}

function dd_dragDuring(ele, mdx, mdy)
{
	xMoveTo(ele, xLeft(ele) + mdx, xTop(ele) + mdy);
	ele.totalMX += mdx;
	ele.totalMY += mdy;

	dz = xGetElementsByAttribute('div','dd_dropzone','true');
	var nfo="";

	
	for(i=0;i<dz.length;i++) {
		if(xIntersection(dz[i],ele)) {

			if(dz[i].getAttribute('dd_accepts_class') ==elementClass(ele)) {
				if(dd_aHover && dd_aHover.id!=dz[i].id) {
					dd_aHover.setAttribute('class',dd_aHover.getAttribute('dd_normal_class'));
				}
				dd_aHover = dz[i];
				dd_aHover.setAttribute('class',dd_aHover.getAttribute('dd_over_class'));
			}
		} else if(dd_aHover.id == dz[i].id) {
			dd_aHover.setAttribute('class',dd_aHover.getAttribute('dd_normal_class'));
			dd_aHover = false;
		}
	}
}

function dd_dragEnd(ele, mx, my)
{
	if(dd_aHover && ele.getAttribute('class')=="thumbnail-drag") {
		dd_aHover.setAttribute('class',dd_aHover.getAttribute('dd_normal_class'));
		dd_aHover.setAttribute('className',dd_aHover.getAttribute('dd_normal_class'));

		if(dd_aHover.onDrop) {
			dd_aHover.onDrop(ele,dd_aHover);
		}
		dd_aHover=false;
	} else if(ele.getAttribute('class')!="thumbnail_drag") {
		if(dd_aHover.onDrop) {
			dd_aHover.onDrop(ele,dd_aHover);
		} else if(ele.onDrop) {
			ele.onDrop(ele,dd_aHover);
		}
	}

	dd_aHover = "";
	dd_aDragging="";
	
	if(elementClass(ele) == "thumbnail-drag") {
		document.body.removeChild(ele);
	} 
}

function elementClass(ele) {
	if(ele.getAttribute('class')) {
		return(ele.getAttribute('class'));
	} else {
		return(ele.getAttribute('className'));	
	}
}

function dd_drop_image(ele, dropzone) {
	e = xGetElementById(ele);

	dz = xGetElementById(dropzone);

	newimg = xCreateElement('img');
	newimg.id = 'lg_'+e.id;
	newimg.setAttribute('src',e.alt);
	newimg.style.position='relative';
	newimg.style.cursor="move";

	if(dz.hasChildNodes()) {
		dz.replaceChild(newimg,dz.firstChild);
	} else {
		dz.appendChild(newimg);
	}
	
	eh = xGetElementById('slider_handle_'+dz.id);
	xLeft(eh,xWidth(eh.parentNode.id) - xWidth(eh));
	dd_addDraggable(newimg.id,0,dd_report);
	recordZone(dz.id);
}

function dd_prepopulate_image(id,upzid,file,dropzone,x,y,w,h,p) {
	dz = xGetElementById(dropzone);
	dz.upzid = upzid;
	newimg = xCreateElement('img');
	newimg.id = 'lg_image_'+id;

	newimg.setAttribute('src',file);
	newimg.style.cursor="move";
	newimg.style.position='relative';
	
	if(dz.hasChildNodes()) {
		dz.replaceChild(newimg,dz.firstChild);
	} else {
		dz.appendChild(newimg);
	}

	dz.firstChild.setAttribute("originalWidth",xWidth(newimg))
	dz.firstChild.setAttribute("originalHeight",xHeight(newimg))

	dz.firstChild.setAttribute("width",xWidth(newimg))
	dz.firstChild.setAttribute("height",xHeight(newimg))
	
	dd_addDraggable(newimg.id,0);

	ele = xGetElementById('lg_image_'+id);
	xLeft(ele,x);
	xTop(ele,y);
	xWidth(ele,w);
	xHeight(ele,h);
	
	slider = xGetElementById("slider_"+dropzone);
	xLeft(slider.firstChild,(p*100));
	
}

function dd_report(ele,notused) {
	e = xGetElementById(ele);
	recordZone(e.parentNode.id);
}


function add_photos() {

	thumbs = xGetElementsByAttribute('img','thumbnail','true');
	for(n=0;n<thumbs.length;n++) {
		items++;
		dd_addDraggable(thumbs[n].id,1);
	}
}

function remove_photo(ele) {
	e=xGetElementById(ele);
	e.parentNode.removeChild(e);

	x_delete_photo(e.id.substr(6),add_cb);
}

function remove_project(ele) {
	e=xGetElementById(ele);
	e.parentNode.removeChild(e);

	x_deleteUserProject(e.id.substr(8),add_cb);
}

// TEXT FUNCTIONS

function sg_textBlock(ele,id,txt,w,h,x,y,ff,fs,fc,fa) {

	e = xGetElementById(ele);

	newzone = xCreateElement('div');

	newzone.id = id;
	newzone.zType = 2;
	newzone.style.position="absolute";
	
	newzone = e.appendChild(newzone);
	
	xWidth(newzone,w);
	xHeight(newzone,h);
	xLeft(newzone,x);
	xTop(newzone,y);

	
	newele = document.createElement('span');
	newele.id = 'textb_'+id;
	newele.style.fontFamily=ff;
	newele.style.fontSize=fs+"px";
	newele.style.position="absolute";
	newele.style.textAlign=fa;
	newele.style.color = fc;

	ne = newzone.appendChild(newele);

	xWidth(ne,w);

	ne.innerHTML = txt;

}

function sg_textBlock_update_text(ele,txt) {
	e = xGetElementById(ele);
	e.innerHTML = txt;
	recordZone(e.parentNode.id);

}

function sg_textBlock_update_color(ele,color) {

	e = xGetElementById(ele);
	e.style.color = color;
	recordZone(e.parentNode.id);

}

function sg_prepopulate_textBlock(ele,upzid,txt,fontface,fontsize,fontcolor,textalign) {

	e = xGetElementById(ele);
	e.firstChild.innerHTML = txt;
	e.firstChild.style.color = fontcolor;
	e.firstChild.style.fontFamily=fontface;
	e.firstChild.style.fontSize=fontsize+"px";
	e.upzid = upzid;

	if(f = xGetElementById("textb_input_"+ele)) {
		f.value=txt
	}
}

// This is Javascript, not PHP!

function js_array_to_php_array (a)
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can 
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie 
// from PHP like this:
//    <?php
//    session_start();
//    $my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
//    print_r ($my_array);
//    ?>
// This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
{
    var a_php = "";
    var total = 0;
    for (var key in a)
    {
        ++ total;
        a_php = a_php + "s:" +
                String(key).length + ":\"" + String(key) + "\";s:" +
                String(a[key]).length + ":\"" + String(a[key]) + "\";";
    }
    a_php = "a:" + total + ":{" + a_php + "}";
    return a_php;
}



zones = new Array();
newcount = 0;
function recordZone(zone) {

		z = xGetElementById(zone);

		data = new Array();	
		upzid = z.upzid;

		if(!upzid) {
			if(z.newZoneIndex) {
				upzid=z.newZoneIndex;
			} else {
				upzid='n'+(newcount);
				z.newZoneIndex = 'n'+newcount;
				newcount++;
			}

		}

		if(z.zType == 1) {
			image = z.firstChild.id.substr(9);
			imagefile = z.firstChild.src;
			x = xLeft(z.firstChild);
			y = xTop(z.firstChild);
			w = xWidth(z.firstChild);
			h = xHeight(z.firstChild);
	
			n=1;
	
			if(z.upzid && z.upzid != "undefined") {
				data["upzid"] = z.upzid;
			} else {
				data["upzid"] = "";
			}
			

			data["pzid"] = zone.substr(4);
			data["upid"] = upid;
			data["ufid"] = z.firstChild.id.substr(9);
			data["filename"] = z.firstChild.src;
			data["pos_x"] = xLeft(z.firstChild);
			data["pos_y"] = xTop(z.firstChild);
			data["width"] = xWidth(z.firstChild);
			data["height"] = xHeight(z.firstChild);
			data["fontface"] = z.firstChild.style.fontFamily;;
			data["fontsize"] = 	z.firstChild.style.fontSize;
			data["textalign"] =	z.firstChild.style.textAlign;		
			data["text"] = z.firstChild.innerHTML;
			
			s = xGetElementById("slider_"+z.id);
			sh = s.firstChild;

			data["percent"] = xLeft(sh) / (xWidth(s));
			data["type"] = 1;
		} else if(z.zType == 2) {
			data["pzid"] = zone.substr(4);
			if(z.upzid) {
				data["upzid"] = z.upzid;
			} else {
				data["upzid"] = "";
			}

			data["ufid"] = 0;
			data["upid"] = upid;
			data["filename"] = "";
			data["pos_x"] = xLeft(z.firstChild);
			data["pos_y"] = xTop(z.firstChild);
			data["width"] = xWidth(z.firstChild);
			data["height"] = xHeight(z.firstChild);
			data["percent"] = 0;
//			data["fontface"] = z.firstChild.style.fontFamily;;
//			data["fontsize"] = 	z.firstChild.style.fontSize.replace("px","");
			data["fontcolor"] = z.firstChild.style.color;
			data["textalign"] =	z.firstChild.style.textAlign.substr(0,1);

			data["text"] = z.firstChild.innerHTML;	
			data["type"] = 2;
		}
		zones["z"+upzid] = new Array();
		zones["z"+upzid] = data;

	serialize_zones();
}

	serialized=new Array();
	
function serialize_zones() {
	serialized = null;

	serialized = new Array();
    for (var key in zones) {
		serialized[key] = js_array_to_php_array(zones[key]);
	}
	serialized = js_array_to_php_array(serialized);
	document.editform.data.value=serialized;

}

function submitPage(action) {
	if(action == -1) {
		document.editform.redirect.value = "books.php";
	} else if(action == -2) {
		document.editform.redirect.value = "index.php?action=logout";
	} else if(action == -3) {
		document.editform.redirect.value = "createPDF_request.php?upid="+upid;
	} else {
		document.editform.redirect.value = "editbook.php?action=load&upid="+upid+"&pagenum="+document.gotoform.page.options[document.gotoform.page.selectedIndex].value;
	}
	document.editform.submit();
}



function sg_toggleSelection(ele) {

	if(ele.getAttribute('selectableType')) {
		for(n=0;n<selection.length;n++) {
	
			if(selection[n].id == ele.id) {
				sg_removeFromSelection(ele);
				return(true);
			}
		}
		sg_addToSelection(ele);
		return(true);
	} else {
		return(false);
	}
}

function sg_selectAll(type) {
	elements = xGetElementsByAttribute('div','selectableType',type);

	for(n=0;n<elements.length;n++) {
		sg_addToSelection(elements[n]);
	}
}

function sg_deSelectAll(type) {
	elements = xGetElementsByAttribute('div','selectableType',type);

	for(z=0;z<elements.length;z++) {
		sg_removeFromSelection(elements[z]);
	}
}

function sg_addToSelection(ele) {

	for(n=0;n<selection.length;n++) {
		if(selection[n].id == ele.id) {
			return(false);
		}
	}

	selection[selection.length] = ele;

	
	if(ele.getAttribute('class')) {
		ele.setAttribute('original_class',ele.getAttribute('class'));
		ele.setAttribute('class',ele.getAttribute('class')+"-selected");
	} else {
		ele.setAttribute('original_class',ele.getAttribute('className'));
		ele.setAttribute('className',ele.getAttribute('className')+"-selected");
	}

}


function sg_removeFromSelection(ele) {
	var i=0;

	newSelection = new Array();
	for(n=0;n<selection.length;n++) {
			
		if(selection[n].id != ele.id) {

			newSelection[i] = selection[n];
			i++;
		}

	}

	selection = newSelection;
	if(ele.getAttribute('class')) {
		ele.setAttribute('class',ele.getAttribute('original_class'));
	} else {
		ele.setAttribute('className',ele.getAttribute('original_class'));
	}
}


function sg_deleteThumbnailSelection(type) {
	if(selection.length==0) {
		return(false);
	}
	
	if(confirm("Are you sure you wish to delete the selection?")) {
		request = new Array();
		request["action"] = "deletePhotos";
	
		for(n=0;n<selection.length;n++) {
			request[request.length] = selection[n].id;
		}
		
		dataField = xGetElementById('serializedData');
		dataField.value = js_array_to_php_array(request);
		
		$form = xGetElementById('serializedRequest');
		$form.submit();
	}
}

function sg_deleteProject(upid) {
	if(confirm("Are you sure you want to delete this project? This will remove your project and any .pdf files you have generated. This can not be undone.")) {
		document.location.href="books.php?action=delete&upid="+upid;
	}
}

function checkSignup() {
	var f = document.signup;
	var ret = true;
	if(f.email.value=="") {
		alert("You must provide a valid email address");
		ret=false;
	}

	if (f.password.value != f.password2.value || f.password.value.length < 5) {
		alert("Passwords do not match or password length too short (5 characters required)");
		ret=false;
	}

	return(ret);	
}
