// IFRAME ONLOAD RESIZING TO ADJUST HEIGHT
function getElement(aID) {
  return (document.getElementById) ?
  document.getElementById(aID) : document.all[aID];
}
function getIFrameDocument(aID){
  var rv = null; 
  var frame=getElement(aID);
  // if contentDocument exists, W3C compliant (e.g. Mozilla) 
  if (frame.contentDocument)
    rv = frame.contentDocument;
  else // bad IE  ;)
    rv = document.frames[aID].document;
  return rv;
}
function adjustiframe_containerHeight(elemId) {
  var frame = getElement(elemId);
  var frameDoc = getIFrameDocument(elemId);
  frame.height = (frameDoc.body.offsetHeight + 100); // pad by 100 extra pixels
}
// END IFRAME ONLOAD RESIZING



function init_ng_app() {
  // build/format tabs
  tabid = 0;
  $$('ul#ng_head_tabs li').each(function(item) {
    if (item.id == '') {
      item.setProperty('id','tab'+tabid);
      tabid++;
    }
    new Element('div').setProperties({'class':'left', 'id':item.id+'_left'}).appendText(' ').injectInside(item);
    m = new Element('div').setProperties({'class':'middle', 'id':item.id+'_middle'}).injectInside(item);
    new Element('p').appendText(item.title).injectInside(m);
    new Element('div').setProperties({'class':'right', 'id':item.id+'_right'}).appendText(' ').injectInside(item);
	item.addEvent('mouseover', function(e) {
	  $(item.id+'_left').setProperty('class','leftover');
	  $(item.id+'_middle').setProperty('class','middleover');
	  $(item.id+'_right').setProperty('class','rightover');
	});
	item.addEvent('mouseout', function(e) {
	  $(item.id+'_left').setProperty('class','left');
	  $(item.id+'_middle').setProperty('class','middle');
	  $(item.id+'_right').setProperty('class','right');
	});
  });
  
  // Apply box formatting
  $$('.box').each(function(item) {
    content = item.innerHTML;
    item.innerHTML = "";
    new Element('div').setProperty('class','boxbar').appendText(item.title).injectInside(item);
    new Element('div').setHTML(content).injectInside(item);
  });
  
  // Apply box formatting
  $$('.box_wide').each(function(item) {
    content = item.innerHTML;
    item.innerHTML = "";
    new Element('div').setProperty('class','boxbar').appendText(item.title).injectInside(item);    
    new Element('div').setStyles({'padding':'5px', 'border':'1px solid #D5D5D5', 'border-top':'0'}).setHTML(content).injectInside(item);
  });
  
  // Apply Mouseover to Content Index categories
  $$('.section li, ul.category_list li').each(function(item) {
    item.addEvent('mouseover', function(e) {
    	item.setStyles({'background-color':'#E0E7F7'});
    });
    item.addEvent('mouseout', function(e) {
    	item.setStyles({'background-color':'#FFF'});
    });
  });

  // Apply Mouseover to box items
  $$('.box li').each(function(item) {
    item.addEvent('mouseover', function(e) {
    	item.setStyles({'background-color':'#E0E7F7'});
    });
    item.addEvent('mouseout', function(e) {
    	item.setStyles({'background-color':'#FFF'});
    });
  });
}


// VIDEO UPLOAD FUNCTIONS
function fileQueued(file, queuelength) {
	var listingfiles = $("SWFUploadFileListingFiles");
	if (!listingfiles.getElementsByTagName("ul")[0]) {
		var ul = document.createElement("ul");
		listingfiles.appendChild(ul);
	}
	listingfiles = listingfiles.getElementsByTagName("ul")[0];
	var li = new Element('li').setProperties({'id':file.id, 'class':'SWFUploadFileItem'});
	li.innerHTML = file.name + " <span class='progressBar' id='" + file.id + "progress'><\/span><div class='progressStat' id='" + file.id + "progress_stat'><\/div><a id='" + file.id + "deletebtn' class='cancelbtn' href='javascript:swfu.cancelFile(\"" + file.id + "\");'><!-- IE --><\/a>";
	listingfiles.appendChild(li);
	$("queueinfo").innerHTML = queuelength + " files queued";
	$(swfu.movieName + "UploadBtn").setStyle('display','block');
	$("cancelqueuebtn").setStyle('display','block');
}

function uploadFileCancelled(file, queuelength) {
	$(file.id).innerHTML = file.name + " - cancelled";
	$(file.id).className = "SWFUploadFileItem uploadCancelled";
	$("queueinfo").innerHTML = queuelength + " files queued";
}

function uploadFileStart(file, position, queuelength) {
	$("queueinfo").innerHTML = "Uploading file " + position + " of " + queuelength;
	$(file.id).className += " fileUploading";
}

function uploadProgress(file, bytesLoaded) {
	var percent = Math.ceil((bytesLoaded / file.size) * 100);
	$(file.id + "progress").setStyle('background-position','-'+(200 - (percent * 2))+'px 0px');
	$(file.id + "progress_stat").innerHTML = percent+"%";
}

function uploadFileComplete(file) {
	$(file.id).className = "SWFUploadFileItem uploadCompleted";
}

function cancelQueue() {
	swfu.cancelQueue();
	$(swfu.movieName + "UploadBtn").setStyle('display','none');
	$("cancelqueuebtn").setStyle('display','none');
}

function uploadQueueComplete(file) {
	$("queueinfo").innerHTML = "All files in queue uploaded! <a href=\"/video_manage.php\">Click here</a> to manage your videos or upload more!"
	$("cancelqueuebtn").setStyle('display','none');
}





function URLEncode(str) {
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var plaintext = str;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";	// x-www-urlencoded, rather than 
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert("Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted.");
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
}


/* MANAGE VIDEO FUNCTIONS */
function load_vid(vid) {
  new Ajax('ajax/video_load.php?vid='+vid+'&rn='+Math.floor(Math.random()*999999), { update: 'vid'+vid } ).request();
}
function save_vid(vid) {
  pdata  = "&rn="+Math.floor(Math.random()*999999);
  pdata += "&id="+vid;
  pdata += "&title="+URLEncode($('vtitle'+vid).value);
  pdata += "&category_id="+URLEncode($('vcategory_id'+vid).value);
  pdata += "&description="+URLEncode($('vdescription'+vid).value);
  pdata += "&tags="+URLEncode($('vtags'+vid).value);
  new Ajax('ajax/video_save.php', { postBody: pdata, update: 'vid'+vid } ).request();
}
function edit_vid(vid) {
  new Ajax('ajax/video_edit.php?vid='+vid+'&rn='+Math.floor(Math.random()*999999), { update: 'vid'+vid } ).request();
}
killvidid = 0;
function delete_vid(vid) {
  var xx = confirm("Are you sure you want to delete this video?");
  if (xx == true) {
    killvidid = vid;
    new Ajax('ajax/video_delete.php?vid='+vid+'&rn='+Math.floor(Math.random()*999999), { update: 'ajax_save', onComplete: fadevid } ).request();
  }
}
function fadevid() {
  $('vid'+killvidid).effect('opacity',{ duration: 500, transition: Fx.Transitions.quadInOut, onComplete: shrinkvid }).start(1,0);
}
function shrinkvid() {
  gc = $('vid'+killvidid).getCoordinates();
  curh = gc['height'];
  $('vid'+killvidid).effect('height',{ duration: 500, transition: Fx.Transitions.quadInOut, onComplete: killvid }).start(curh,0);
}
function killvid() {
  $('vid'+killvidid).remove();
  killvidid = 0;
}
function toggle_edit_comments(vid) {
  if ($('editcomments'+vid).style.display == "none") {
    $('editcomments'+vid).setStyle('display','');
  }
  else {
    $('editcomments'+vid).setStyle('display','none');
  }
}
killcommid = 0;
function delete_comment(id,vid) {
  var xx = confirm("Are you sure you want to delete this comment?");
  if (xx == true) {
    killcommid = id;
    new Ajax('ajax/delete_comment.php?id='+id+'&rn='+Math.floor(Math.random()*999999), { update: 'ajax_save', onComplete: fadecomment } ).request();
    tcc = parseInt($('TCC'+vid).innerHTML);
    tcc--;
    $('TCC'+vid).innerHTML = tcc;
    if (tcc == 0) {
      toggle_edit_comments(vid);
    }
  }
}
function fadecomment() {
  $('comment'+killcommid).effect('opacity',{ duration: 500, transition: Fx.Transitions.quadInOut, onComplete: shrinkcomm }).start(1,0);
}
function shrinkcomm() {
  gc = $('comment'+killcommid).getCoordinates();
  curh = gc['height'];
  $('comment'+killcommid).effect('height',{ duration: 500, transition: Fx.Transitions.quadInOut, onComplete: killcomm }).start(curh,0);
}
function killcomm() {
  $('comment'+killcommid).remove();
  killcommid = 0;
}

function read_more(vid) {
  if ($('short_desc'+vid).style.display == 'none') {
    $('short_desc'+vid).setStyle('display','');
    $('long_desc'+vid).setStyle('display','none');
  }
  else {
    $('short_desc'+vid).setStyle('display','none');
    $('long_desc'+vid).setStyle('display','');
  }
}

function init_cms_menu() {
  $$('ul.cms_menu li').each(function(item){
	item.addEvent('mouseover', function(e) {
	  item.setStyles({'color':'#AB0B25', 'background-color':'#DBDBDB', 'border':'1px solid #AB0B25'});
	});
	item.addEvent('mouseout', function(e) {
	  item.setStyles({'color':'#0000FF', 'background-color':'#FFFFFF', 'border':'1px solid #CCC'});
	});
  });
}

function editCat(id) {
  window.location = "?action=edit&id="+id;
}
function deleteCat(id,tr,lbl) {
  if (tr > 0) {
    alert("This category cannot be deleted because there are currently "+lbl+" assigned to it.");
  }
  else {
    var kk = confirm("Are you sure you want to delete this category?");
    if (kk == true) {
      window.location = "?action=delete&id="+id;
    }
  }
}

function editSubCat(id,pid) {
  window.location = "?action=edit&id="+id+"&pid="+pid;
}
function deleteSubCat(id,tr,lbl,pid) {
  if (tr > 0) {
    alert("This category cannot be deleted because there are currently "+lbl+" assigned to it.");
  }
  else {
    var kk = confirm("Are you sure you want to delete this category?");
    if (kk == true) {
      window.location = "?action=delete&id="+id+"&pid="+pid;
    }
  }
}

function chkCatForm() {
  if (document.catform.name.value == "") {
    alert("Please enter a category name.");
    document.catform.name.focus();
    return false;
  }
  else {
    document.catform.subtn.value = "saving...";
    document.catform.subtn.disabled = true;
    return true;
  }
}
function init_cms_list_sort(tbl) {
	new Sortables($('mylist'), {
		handles: 'img.handle',
		onComplete: function () {
		    idstr = myserialize($('mylist'), {key: 'sid', tag: 'li'});
			new Ajax('/ajax/category_sort.php', { postBody:'&tbl='+tbl+'&'+idstr, update:'ajax_save' } ).request();
		}
	});
}

function myserialize(element, options){
  var str = [];
  var key = encodeURIComponent(options.key || element.id);
  var elements = $A(element.getElements(options.tag || ''));
  elements.each(function(el, i) {
    str.push(key+'['+i+']='+el.id);
  });
  return str.join('&');
}

function classified_sub_cat(pid) {
  window.location = '/cms_classified_subcategories.php?pid='+pid;
}

function reorder_cats(pid) {
  if (!pid) {
    pid = "";
  }
  else {
    pid = "&pid="+pid;
  }
  var rr = confirm("This will reorder all categories in alphabetical order. Your current custom order will be overwritten. Are you sure you wish to proceed?");
  if (rr == true) {
    window.location = "?action=reorder"+pid;
  }
}



function bookmarksite(title,url) {
  if (window.sidebar) { // firefox
	window.sidebar.addPanel(title, url, "");
  }
  else if (window.opera && window.print) { // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
  } 
  else if (document.all) { // ie
	window.external.AddFavorite(url, title);
  }
}