
/** Open popup window.
 * @param string url       url to open in popup window
 * @param string name      window name
 * @param int    width     window width
 * @param int    height    window height
 * @param bool   bIsResize true - window resizable, false - fixed size
 */
function openWin(url, name, width, height, bIsResize){
  if (!width)
        width = screen.width*0.9;
  if (!height)
        height = screen.height*0.75;
  IsReize = bIsResize?1:0;
  var newWindow = window.open(url, name, 'left=' + Math.ceil((screen.width - width)/2) + ',top=' + Math.ceil((0+screen.height - height)/2) + ',width=' + width + ',height=' + height + ',location=0,toolbar=0,directories=0,status=0,menubar=0,scrollbars=1,resizable='+bIsResize+',channelmode=0,fullscreen=0');
  return false;
}


/** Selects/deselects all checkbox with given name
 * @param string name checbox name
 * @param bool   val  true - select, false - deselect boxes
 */
function selectAll(name,val){
        a = document.getElementsByName(name);
        for(i=0;i<a.length;++i) {
                a[i].checked =   val;
        }
}

/** Returns value of selected item (singel or first for multiselect)
 *  in SELECT element.
 * @param string sName select element name
 * @return mixed selected element value or 0 - if none selected
 */
function getSelectedId( sName ){
        var a = document.getElementsByName(sName);
        for(i=0;i<a.length;++i)
                if(a[i].checked) return a[i].value;
        return 0;
}

/** Clear form elements. Used insted reset() when neede clear elements
 *  but not reset to start values.
 * @param string formName name form to clear
 */
function clearForm(formName)
{
        formName.reset();
        var a = formName.elements;
        for(i=0;i<a.length;++i)
        {
                type_input = a[i].type.toLowerCase();
                if(type_input == 'select-one') {
                        a[i].selectedIndex = 0;
                } else if (type_input == 'checkbox') {
                        a[i].checked = false;
                } else if (type_input == 'file') {
                } else if (type_input == 'submit') {
                } else if (type_input == 'button') {
                } else {
                        a[i].value = '';
                }
        }
}



/** Inserts text in textarea (replaces selection or insert to the end of text)
 * @param object oTextArea textarea object
 * @param string sText     text to insert
 * @return bool true
 */
function insertToTextArea(oTextArea, sText) {
    //for IE
    if (document.selection) {
            oTextArea.focus();
            oSel = document.selection.createRange();
            oSel.text = sText;
    }
    //for MOZILLA/NETSCAPE
    else if (oTextArea.selectionStart || oTextArea.selectionStart == "0") {
            var startPos  = oTextArea.selectionStart;
            var endPos    = oTextArea.selectionEnd;
            var str       = oTextArea.value;

            oTextArea.value = str.substring(0, startPos) + sText + str.substring(endPos, str.length);
    } else {
            oTextArea.value += sText;
    }

    return true;
}

function setCookie(name, value)
{
var cookie_date = new Date ( 2099, 01, 01 );
document.cookie = name+"="+value+"; expires=" + cookie_date.toGMTString();
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function textCounter(field, maxlimit) 
{
    if (!field) return;
    if (field.value.length > maxlimit) 
    {
        field.value = field.value.substring(0, maxlimit);
    }
    
}

function autotab(original,destination,key)
{
    if (key>=32 && original.getAttribute && original.value.length==original.getAttribute("maxlength"))
    {
        destination.focus();
        destination.select();
    }
}

function menuhide(menunum)
{
    var currentmenu = document.getElementById("new_navbody" + menunum);
    currentmenu.style.visibility = 'hidden';
}

function menushow(menunum)
{
    var currentmenu = document.getElementById("new_navbody" + menunum);
    currentmenu.style.visibility = 'visible';
}

function selectArea(sKey)
{
    var oForm = document.getElementById('form_area');

    if (oForm)
    {
        oForm.action = sKey;
    }
}

function changeSelectElText(sVal, sColor)
{
    document.getElementById('select_el').innerHTML = sVal;
    document.getElementById('select_el').style.color = sColor;
}
    
function checkInput(oInput, bFocus, sCheckDefText, sClassName)
{
    if (!oInput) return false;
 
    if (bFocus)
    {
	    if (oInput.value && oInput.value == sCheckDefText)
	    {
	        oInput.className = sClassName;
	        oInput.value = '';
	    }
    }
    else
    {
	    if (!oInput.value || oInput.value == sCheckDefText)
	    {
	        oInput.className = sClassName + ' grey_text';
	        oInput.value = sCheckDefText;
	    }
    }
}

function checkSubmit(sInputId, sCheckDefText)
{
    oInput = document.getElementById(sInputId);
    
    if (oInput.value && oInput.value == sCheckDefText)
    {
        oInput.focus();
        return false;
    }
    return true;
}

function toggleMoreLess(sDivId, sAnchorId, sHeight)
{
	var oDiv = document.getElementById(sDivId);
	var oAnchor = document.getElementById(sAnchorId);
	if(oDiv.style.cssText && oDiv.style.cssText.toLowerCase().match("overflow") == null)
	{
		oDiv.style.cssText = "margin:0; padding:0; overflow-x:hidden; overflow-y:hidden; height:" + sHeight;
		oAnchor.innerHTML="(more)";
	}
	else if(oDiv.style.cssText && oDiv.style.cssText.toLowerCase().match("overflow") != null)
	{
		oDiv.style.cssText = "margin:0; padding:0; min-height:" + sHeight;
		oAnchor.innerHTML="(less)";
	}
	else
	{
		alert("Your browser does not support this function. Please click the title of the plick to view the full description.");
	}
}

function toggleTinyMCE(sElementId, bIsAdvanced)
{
	if(bIsAdvanced)
	{
		tinyMCE.execCommand('mceRemoveControl', false, sElementId);
		tinyMCE.init({
			// General options
			mode : "exact",
			elements : sElementId,
			theme : "advanced",
			plugins : "safari,table,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,searchreplace,contextmenu,paste,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,media",
			cleanup_on_startup : true,
	
			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,insertdate,inserttime,|,forecolor,backcolor",
			theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,link,unlink,anchor,image,media,cleanup,help,code",
			theme_advanced_buttons4 : "cut,copy,paste,pastetext,pasteword,|,tablecontrols",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
	
			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js",
		
			setup: function(ed) {
			    // Force Paste-as-Plain-Text
			    ed.onPaste.add( function(ed, e, o) {
			        ed.execCommand('mcePasteText', true);
			        return tinymce.dom.Event.cancel(e);
			    });
			}
		});
	}
	else
	{
		tinyMCE.execCommand('mceRemoveControl', false, sElementId);
		tinyMCE.init({
			// General options
			mode : "exact",
			elements : sElementId,
			theme : "simple",
			plugins : "paste",
			cleanup_on_startup : true,
		
			setup: function(ed) {
			    // Force Paste-as-Plain-Text
			    ed.onPaste.add( function(ed, e, o) {
			        ed.execCommand('mcePasteText', true);
			        return tinymce.dom.Event.cancel(e);
			    });
			}
		});
	}
}

function toggleAdvancedSimple(oAnchor)
{
	if(oAnchor.innerHTML.match("advanced"))
	{
		oAnchor.onclick = function(){toggleTinyMCE('plick_textarea', false); toggleAdvancedSimple(this); return false;};
		oAnchor.innerHTML = "(simple editing)";
	}
	else
	{
		oAnchor.onclick = function(){toggleTinyMCE('plick_textarea', true); toggleAdvancedSimple(this); return false;};
		oAnchor.innerHTML = "(advanced editing)";
	}
}

function toggleCustomResize(oSelect)
{
	var div0 = document.getElementById("divCustomWidthLabel");
	var div1 = document.getElementById("divCustomWidthValue");
	var div2 = document.getElementById("divCustomHeightLabel");
	var div3 = document.getElementById("divCustomHeightValue");

	if(oSelect.options.length-1 == oSelect.selectedIndex)
	{
		if(div0.style.cssText != undefined)
		{
			div0.style.cssText = div1.style.cssText = div2.style.cssText = div3.style.cssText = "";
		}
		if(div0.style.display != undefined)
		{
			div0.style.display = div1.style.display = div2.style.display = div3.style.display = "";
		}
		
	}
	else
	{
		if(div0.style.cssText != undefined)
		{
			div0.style.cssText = div1.style.cssText = div2.style.cssText = div3.style.cssText = "display:none";
		}
		if(div0.style.display != undefined)
		{
			div0.style.display = div1.style.display = div2.style.display = div3.style.display = "none";
		}
	}
}

function updateCustom(oInput)
{
	if(oInput.id == "customWidth")
	{
		if(oInput.value == "")
		{
			oInput.disabled = false;
			document.getElementById('customHeight').disabled = false;
			document.getElementById('customHeight').value = "";
		}
		else
		{
			document.getElementById('customHeight').disabled = true;
			document.getElementById('customHeight').value = "Auto";
		}
	}
	else
	{
		if(oInput.value == "")
		{
			oInput.disabled = false;
			document.getElementById('customWidth').disabled = false;
			document.getElementById('customWidth').value = "";
		}
		else
		{
			document.getElementById('customWidth').disabled = true;
			document.getElementById('customWidth').value = "Auto";
		}
	}
}
function changeForm(sType, oButton)
{
	document.getElementById("linkShareForm").style.cssText = "display:none";
	document.getElementById("picShareForm").style.cssText = "display:none";
	document.getElementById("plickShareForm").style.cssText = "display:none";
	document.getElementById("uploadPicsButton").disabled = false;
	document.getElementById("exploreLinksButton").disabled = false;
	oButton.disabled = true;
	document.getElementById(sType + "ShareForm").style.cssText = "";
}
function toggleAdvanced(sTableId)
{
	if(document.getElementById(sTableId).style.cssText.length > 0)
	{
		document.getElementById(sTableId).style.cssText = "";
	}
	else
	{
		document.getElementById(sTableId).style.cssText = "display:none";
	}
}
function togglePicSource(iInputIndex)
{
	var tmp = document.getElementById('picFile' + iInputIndex).style.cssText;
	document.getElementById('picFile' + iInputIndex).style.cssText = document.getElementById('fileURL' + iInputIndex).style.cssText;
	document.getElementById('fileURL' + iInputIndex).style.cssText = tmp;
	document.getElementById('isURL' + iInputIndex).value == "" ? document.getElementById('isURL' + iInputIndex).value = "yes" : document.getElementById('isURL' + iInputIndex).value = "";
}
function validateShareForm(oForm)
{
	var errors = "";
	if(oForm.id.match("pic"))
	{
		var atLeastOnePic = false;
		var iPicCount = document.getElementById('picCount').value;
		for(var i = 1; i <= iPicCount; i++)
		{
			if(oForm["picFile"+i].value != null && oForm["picFile"+i].value.length != 0)
			{
				atLeastOnePic = true;
				break;
			}
			else if(oForm["fileURL"+i].value != null && oForm["fileURL"+i].value.length != 0)
			{
				atLeastOnePic = true;
				break;
			}
		}
		if(!atLeastOnePic)
		{
			errors = errors + "You must supply at least one pic.\n";
		}
	}
	else if(oForm.id.match("plick"))
	{
		if(oForm["picFile"].value == null || oForm["picFile"].value.length == 0)
		{
			errors = errors + "You must supply a pic.\n";
		}
	}
	
	if(errors.length > 0)
	{
		alert(errors);
		return false;
	}
	
	return true;
}
function shareAddPicField()
{
	var table = document.getElementById('picListTable');
	var newRow = table.insertRow(table.rows.length);
    var newCell = newRow.insertCell(0);
    document.getElementById('picCount').value++;
    var picCount = document.getElementById('picCount').value;
    newCell.innerHTML = '<label for="picFile' + picCount + '" style="font-size:14px"><strong>' + picCount + '.</strong>&nbsp;</label>' + "\n" + '<input type="file" name="picFile' + picCount + '" id="picFile' + picCount + '" class="shareFileField" />' + "\n" + '<input type="text" name="fileURL' + picCount + '" id="fileURL' + picCount + '" class="shareTextField" style="display: none" />&nbsp;' + "\n" + '<input type="hidden" name="isURL' + picCount + '" id="isURL' + picCount + '" value="" onclick="togglePicSource(' + picCount + ')"><label for="isURL' + picCount + '" class="share_bgButtonText" onclick="this.innerHTML.match(\'From URL\') == null ? this.innerHTML=\'From URL\' : this.innerHTML=\'Computer\';">From URL</label></input>';
}
function shareRemovePicField()
{
	var table = document.getElementById('picListTable');
	var newRow = table.deleteRow(table.rows.length-1);
	document.getElementById('picCount').value--;
}
function updateEmbedCodeBox(codeSelector)
{
	var newCode = "";
	var type = parseInt(codeSelector.options[codeSelector.selectedIndex].value);
	for(var i = 0; i < shareNumPics; i++)
	{
		caption = document.getElementById('caption'+i).value;
		bSmallThumbnails = document.getElementById('smallThumbnails').checked;
		bLargeThumbnails = document.getElementById('largeThumbnails').checked;
		if(i > 0)
		{
			newCode += "\n\n";
		}
		switch(type)
		{
		case 0:
			if(caption.length > 0)
			{
				newCode = newCode + "[B]" + caption + "[/B]\n";
			}
			if(bSmallThumbnails)
			{
				newCode = newCode + bbCodesSmallThumbs[i];
			}
			else if(bLargeThumbnails)
			{
				newCode = newCode + bbCodesLargeThumbs[i];
			}
			else
			{
				newCode = newCode + bbCodesNoThumbs[i];
			}
			break;
		case 1:
			if(caption.length > 0)
			{
				newCode = newCode + "<strong>" + caption + "</strong>\n";
			}
			if(bSmallThumbnails)
			{
				newCode = newCode + htmlCodesSmallThumbs[i];
			}
			else if(bLargeThumbnails)
			{
				newCode = newCode + htmlCodesLargeThumbs[i];
			}
			else
			{
				newCode = newCode + htmlCodesNoThumbs[i];
			}
			break;
		case 2:
			newCode = newCode + directURLs[i];
			if(caption.length > 0)
			{
				newCode = newCode + " - " + caption;
			}
			break;
		default:
			alert('hi');
			break;
		}
	}
	document.getElementById("embedCodeBox").value = newCode;
}
function swapValues(objA, objB)
{
	var tmp = objA.value;
	objA.value = objB.value;
	objB.value = tmp;
}
function swapInnerHTML(objA, objB)
{
	var tmp = objA.innerHTML;
	objA.innerHTML = objB.innerHTML;
	objB.innerHTML = tmp;
}
function exchangeRows(cell0, cell1)
{
	var tmp;
	var idx0 = parseInt(cell0.substr(4));
	var idx1 = parseInt(cell1.substr(4));
	swapValues(document.getElementById("caption"+idx0), document.getElementById("caption"+idx1));
	swapInnerHTML(document.getElementById(cell0), document.getElementById(cell1));
	
	tmp = directURLs[idx0];
	directURLs[idx0] = directURLs[idx1];
	directURLs[idx1] = tmp;
	
	tmp = bbCodesSmallThumbs[idx0];
	bbCodesSmallThumbs[idx0] = bbCodesSmallThumbs[idx1];
	bbCodesSmallThumbs[idx1] = tmp;
	
	tmp = htmlCodesSmallThumbs[idx0];
	htmlCodesSmallThumbs[idx0] = htmlCodesSmallThumbs[idx1];
	htmlCodesSmallThumbs[idx1] = tmp;
	
	tmp = bbCodesLargeThumbs[idx0];
	bbCodesLargeThumbs[idx0] = bbCodesLargeThumbs[idx1];
	bbCodesLargeThumbs[idx1] = tmp;
	
	tmp = htmlCodesLargeThumbs[idx0];
	htmlCodesLargeThumbs[idx0] = htmlCodesLargeThumbs[idx1];
	htmlCodesLargeThumbs[idx1] = tmp;
	
	tmp = bbCodesNoThumbs[idx0];
	bbCodesNoThumbs[idx0] = bbCodesNoThumbs[idx1];
	bbCodesNoThumbs[idx1] = tmp;
	
	tmp = htmlCodesNoThumbs[idx0];
	htmlCodesNoThumbs[idx0] = htmlCodesNoThumbs[idx1];
	htmlCodesNoThumbs[idx1] = tmp;
	
	tmp = bbCodeCaptions[idx0];
	bbCodeCaptions[idx0] = bbCodeCaptions[idx1];
	bbCodeCaptions[idx1] = tmp;
	
	tmp = htmlCodeCaptions[idx0];
	htmlCodeCaptions[idx0] = htmlCodeCaptions[idx1];
	htmlCodeCaptions[idx1] = tmp;
	
	tmp = directURLCaptions[idx0];
	directURLCaptions[idx0] = directURLCaptions[idx1];
	directURLCaptions[idx1] = tmp;
	
	updateEmbedCodeBox(document.getElementById('embedCodeType'));
}
function togglePicsMoreInfo()
{
	if(document.getElementById('picMoreInfo').style.cssText.length > 0)
	{
		document.getElementById('picMoreInfo').style.cssText='';
	}
	else
	{
		document.getElementById('picMoreInfo').style.cssText='display:none';
	}
}
