// Relies on Browser.js include "browser.js";
var viewMode = 1;

function _getSelection( theWindow )
{
	if (browser.isIE) {
		return theWindow.document.selection;
	} else {
		return theWindow.getSelection();
	}
		
}

function _getRange( sel, theWindow )
{
	if (browser.isIE) {
		return sel.createRange();
	} else {
		theWindow.focus();
		//iView.window.focus();
		//this.focusEditor();
		if (typeof sel != "undefined") {
			return sel.getRangeAt(0);
		} else {
			return theWindow.document.createRange();
		}
	}	
}

function _setViewMode( viewMode )
{
	if ( browser.isIE )
	{
		_getDocument('iView').body.contentEditable = true;
	}
	else
	{
		iView.document.designMode = 'On';	
	}
}

function _execCommand( id, command, userInterface, value )
{
	document.getElementById( id ).contentWindow.focus();
	_getDocument( id ).execCommand( command, userInterface, value );
	
}

// REturns the IFrame document, given the iframe ID
function _getDocument(aID) 
{
	// if contentDocument exists, W3C compliant (Mozilla)
	if ( browser.isIE )
	{
		  // IE
		  return document.frames[aID].document;
	} 
	else 
	{
		return document.getElementById(aID).contentDocument;
	}

}

/** Inserts a table given a id that has two fields ( table_rows, tabel_columns ) */
function insertTableByProperties( target, propertiesName )
{
	var props = document.getElementById( propertiesName );
	
	if ( !props )
		return;
	
	var rows = document.getElementById( "table_rows" )
	var columns = document.getElementById( "table_columns" )
	
//	var rows = props.table_rows.nodeValue;
	//var columns = props.table_columns.nodeValue;

	insertTable( target, rows.value, columns.value );
}
/** Inserts an image given the data from a pop-up window */
function insertImagePopup()
{
	var iFrame = document.getElementById("iView");
	// USES HtmlArea Dialog boxes
	
	var window = iFrame.contentWindow;
	var docu = iFrame.contentDocument;
	
	Dialog("includes/html/formatting/insert_image.html", function(param) {
		if (!param) {	// user must have pressed Cancel
			return false;
		}
		var sel = _getSelection(window);
		var range = _getRange(sel,window);
		docu.execCommand("insertimage", false, param["f_url"]);
		var img = null;
	/*	if (HTMLArea.is_ie) {
			img = range.parentElement();
			// wonder if this works...
			if (img.tagName.toLowerCase() != "img") {
				img = img.previousSibling;
			}
		} else {
			img = range.startContainer.previousSibling;
		}
		for (field in param) {
			var value = param[field];
			if (!value) {
				continue;
			}
			switch (field) {
			    case "f_alt"    : img.alt	 = value; break;
			    case "f_border" : img.border = parseInt(value); break;
			    case "f_align"  : img.align	 = value; break;
			    case "f_vert"   : img.vspace = parseInt(value); break;
			    case "f_horiz"  : img.hspace = parseInt(value); break;
			}
		}*/
	}, null);
	
}

/** Inserts a table given the data from a pop-up window */
function insertTablePopup()
{
	var iFrame = document.getElementById("iView");
	// USES HtmlArea Dialog boxes
	var sel = _getSelection(iFrame.contentWindow);
	var range = _getRange(sel, iFrame.contentWindow);
	
	var thisdoc = _getDocument("iView");	// for nested functions
	
	Dialog("includes/html/formatting/insert_table.html", function(param) {
		if (!param) {	// user must have pressed Cancel
			return false;
		}
		var doc = thisdoc;
		// create the table element
		var table = doc.createElement("table");
		// assign the given arguments
		for (var field in param) {
			var value = param[field];
			
			if (!value) {
				continue;
			}
			switch (field) {
			    case "f_width"   : table.style.width = value + param["f_unit"]; break;
			    case "f_align"   : table.align	 = value; break;
			    case "f_border"  : table.border	 = parseInt(value); break;
			    case "f_spacing" : table.cellspacing = parseInt(value); break;
			    case "f_padding" : table.cellpadding = parseInt(value); break;
			}
		}
		var tbody = thisdoc.createElement("tbody");
		table.appendChild(tbody);
		for (var i = 0; i < param["f_rows"]; ++i) {
			var tr = thisdoc.createElement("tr");
			tbody.appendChild(tr);
			for (var j = 0; j < param["f_cols"]; ++j) {
				var td = thisdoc.createElement("td");
				tr.appendChild(td);
				// Mozilla likes to see something inside the cell.
				if ( browser.isNS )
					td.appendChild(thisdoc.createElement("br"));
			}
		}
		if (browser.isIE) {
			range.pasteHTML(table.outerHTML);
		} else {
			// insert the table
			insertNodeAtSelection(table);
		}
		return true;
	}, null);
	
	
	
	/*if ( win )
		alert( "Yes" );
	else
		alert( "No" );*/
	//_execCommand( 'iView', 'forecolor', false, win.returnValue);
}

function insertTable( target, numrows, numcolumns )
{
	var target = document.getElementById( target );
	var table = document.createElement("table");
	
	table.setAttribute("border", "1");
	
	var tbody = document.createElement("tbody");
	var y = 0;
	
	
	for ( var rows = 0; rows < numrows; rows++ )
	{
		var tr = document.createElement("tr");
	
		for ( var cols = 0; cols < numcolumns; cols++ )
		{
			var td = document.createElement("td");
			    var td_text = document.createTextNode("text")
			    td.appendChild(td_text)
			tr.appendChild( td );
			
		}
		
		tbody.appendChild( tr );
		
	}
	
	table.appendChild(tbody)
 
    	target.appendChild(table)
	
	
}

function changeBackground( object, newValue )
{
	var obj = document.getElementById( object );
	obj.setAttribute("text-color", "#FF0000");
}


function insertTextHTMLAreaCallback( wind, target, textarea )
{
	// Html area edit boxes are stored in an IFRAME, so require special access to get the html of it.
	// First you need to get the IFRAME of the HtmlArea object, then find the document for it, then find the body and lastly use body.innerHTML.
	
	// This does require though, that you have the htmlarea element wrappend in an extra div tag like so:
	// <div myid>
	//  	<textarea>
	// </div>
	var thisTarget =wind.document.getElementById( target );
	
	if (!thisTarget)
		alert('No');
	// Retrieve 
	var object = document.getElementById( textarea );
	
	var frame = object.getElementsByTagName( "IFRAME" );
		
	thisTarget.innerHTML = frame[0].contentDocument.body.innerHTML;
}

function insertText( object )
{
	var obj = document.getElementById( object );

	var winRef = window.open('admin.php?name=cms_new&file=textWindow&target='+object+'','Text Properties','width=600,height=400');
	
	winRef.document.getElementById('h').value = "fds";
	
}

/** Changes the 'action' field of a form to 'newtarget'.  If redirect is true, then the form will be submitted */
function redirectForm( formname, newtarget, redirect )
{
	// Store the old location for further use
	var oldLocation = document.forms[formname].action;

	// Assign the new location
	document.forms[formname].action = newtarget;

	if ( redirect )
		document.forms[formname].submit();
}





function doSaveCampaign( formname, newtarget )
{
	// Change the form to load the new php file that will in turn save the contents or the campaign
	redirectForm( formname, newtarget );
	doTemplateSubmit( formname );
}


function doTemplateSubmit( formName )
{
	var html = '';
	var childNode;
	
	for ( var child = 0; child < iView.document.childNodes.length; child++ )
	{
		childNode = iView.document.childNodes[child];
		if ( childNode.name == "HTML" )
		{
			//html += 	childNode.publicId;
			//html += 	childNode.systemId;
		}
		
		if ( browser.isIE )
			html = childNode.innerHTML;
		else
			html = childNode.innerHTML;
			
	}
	
//	if ( !browser.isIE )
//		alert( html );

	document.getElementById('htmlContent').value = html;
	
	document.campaign_2.submit();
}

function doSMSSubmit( formName )
{
	var html = '';
	var childNode;
		
	document.campaign_2.submit();
}


function doDesignMode()
{
	 if(viewMode == 1)
	{
		viewMode = 2; // Code
	}
	else
	{
		viewMode = 1; // WYSIWYG
	} 
	
	_setViewMode( viewMode );
//	_getDocument('iView').focus();
document.getElementById('iView').contentWindow.focus();		
	//iView.document.designMode = 'On';	
}

function getPersonaliseSelectionValue( from )
{
	var field = document.getElementById( from );
	
	var seperator = field.value.indexOf(",");
	
	var fieldDB = field.value.substr( 0, seperator );
	var fieldName = field.value.substr( seperator+1, field.value.length );

	return  "&lt;&lt;" + fieldName + "&gt;&gt;";
}

function addFieldElementToWindow( from, targetWindow )
{
	var field = document.getElementById( from );
	
	var seperator = field.value.indexOf(",");
	
	var fieldDB = field.value.substr( 0, seperator );
	var fieldName = field.value.substr( seperator+1, field.value.length );
	
	if ( fieldName == '' )
		return;
	
	//wp_current_ob.insertAtSelection( "<<" + fieldName + ">>" );
	/*var text = _getDocument('iView').createTextNode( "<<" + fieldName + ">>" );

	insertNodeAtSelection(text);*/
}


function doBold() { _execCommand( 'iView', 'bold', false, null); }

function doItalic() { _execCommand( 'iView', 'italic', false, null); }

function doUnderline() { _execCommand( 'iView', 'underline', false, null); }

function doJustifyLeft() { _execCommand( 'iView', 'justifyleft', false, null); }

function doJustifyCenter() { _execCommand( 'iView', 'justifycenter', false, null); }

function doJustifyRight() { _execCommand( 'iView', 'justifyright', false, null); }

function doJustifyJustified() { _execCommand( 'iView', 'justifyfull', false, null); }

function doInsertTable() { 
	//var sel = this._getSelection();
	//var range = this._createRange(sel);
	insertTablePopup();
	//insertTable( "iView", 2, 2 );	
	
	//alert(sel.text);
//_execCommand( 'iView', 'inserttable', false, null); }
}

function doInsertImage()
{
	insertImagePopup();	
}

function doForeCol() {
//	Msg = "Please type the colour or hex value you wish to use on the selected text.";
//	if (forecolor = prompt(Msg,"red")) _execCommand( 'iView', 'forecolor', false, forecolor);
	Dialog("includes/html/formatting/select_color.html", 
			function(color) {
				if (color) { // selection not canceled
					_execCommand( 'iView', 'forecolor', false, "#" + color);
			}}, null );
	
}

function doBackCol() {
	//Msg = "Please type the colour or hex value you wish to use on the background of the selected text.";
	//if(bCol = prompt (Msg, "red")) _execCommand( 'iView', 'backcolor', false, bCol);
	Dialog("includes/html/formatting/select_color.html", 
			function(color) {
				if (color) { // selection not canceled
					if ( !browser.isIE )
						_execCommand( 'iView', 'hilitecolor', false, "#" + color);
					else
						_execCommand( 'iView', 'backcolor', false, "#" + color);
			}}, null );

}

function doToggleTextMode( id1, id2 ) {
	toggleHidden( id1 );
	toggleHidden( id2 );
}

function doToggleUserImages( id )
{
	toggleHidden( id );
}

function doUndo()
{
	_execCommand( 'iView', 'undo', false, null);
}

function doRedo()
{
	_execCommand( 'iView', 'redo', false, null);
}

function doFont( fontName )
{
	 if( fontName != '' )
		 _execCommand( 'iView', 'fontname', false, fontName); 
}

function doHeading( headingName )
{
	
}

function doFontSize()
{
	
}

function doHightlightColor() {
	if(bCol = prompt ("", "red")) _execCommand( 'iView', 'hilitecolor', false, bCol);
	
}

function doLink() { 
	 var str=prompt("Enter link location (e.g. http://www.google.com):", "http:\/\/");
	_execCommand( 'iView', 'createlink', false, str); 
}

function doSelectFormat( selectname, destnWindow )
{
	var cursel = document.getElementById(selectname).selectedIndex;
	
	/* First one is always a label */
	if (cursel != 0) {
		var selected = document.getElementById(selectname).options[cursel].value;
		
		document.getElementById(destnWindow).contentWindow.document.execCommand(selectname, false, selected);
		document.getElementById(selectname).selectedIndex = 0;
	}
}



function textFieldCounter(field,cntfield,maxlimit)
{
	var counterText = document.getElementById( cntfield );
	
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	else
		counterText.innerHTML = maxlimit - field.value.length;
}



function insertNodeAtSelection( node, destinationNode )
{
	var iFrame = document.getElementById( 'iView' );
	
	var sel = _getSelection( iFrame.contentWindow );
	var range = _getRange( sel, iFrame.contentWindow );
	
	if (browser.isIE) {
		switch (node.nodeType) {
			    case 3: // Node.TEXT_NODE
			    {
				    range.text = node.nodeValue;
			    }
			    break;
			    case 1:
			    {
					range.pasteHTML( node.outerHTML );
					
			    }
			    break;
		}
	}
	else
	{
		sel.removeAllRanges();
		
		// Delete all content already in this selection range
		range.deleteContents();
						
		range.insertNode( node );	
		
	}
	//node.createNode(
}

function toggleHidden( id )
{
	var element = document.getElementById( id );

	if ( element )
	{
		// Check the element style, set to hidden if not and visibile if hidden
		if ( element.style.display == "none" )
		{
			element.style.display = "block";
		}
		else 
		{
			element.style.display = "none";
		}	
	}
}

// Toggles all check boxes in a form, given a prefix, and limit (num)
function ToggleCheckAllForm( formName, prefix, num )
{
	var toggle = document.forms[formName].toggle.checked;
	
	var n2  = 0;
	for (i=0; i < num; i++) 
	{
		cb = eval( 'document.forms[formName].'+prefix + i );
		if (cb) 
		{
			cb.checked = toggle;
			n2++;
		}
	}

	if (toggle) {
			document.forms[formName].boxchecked.value = n2;
	} else {
			document.forms[formName].boxchecked.value = 0;
	}
}


// Called when a check box is clicked.  For use in forms that use ToggleCheckAllForm etc.  The form must have
// a member called boxchecked
function Checked( formName, isChecked )
{
	var form = document.forms[formName];
	if ( form )
	{
		if ( isChecked )
			form.boxchecked.value++;
		else
			form.boxchecked.value--;
	}
}

function SubmitForm2( formName, op )
{
	var form = document.forms[formName];

	if ( form )
	{
		var x = form.elements;

		for (var i=0;i<x.length;i++)
		{
			if (x[i].getAttribute('required') && !x[i].value)
			{
				
				return false;
			}
		}
		
		form.op.value = op;
		form.submit();
	}
	else
		return false;
	

return true;

}

function OpenWindow( url, name, options )
{
	newWindow = window.open( url, name, options );

	if ( newWindow.focus )
	{
		newWindow.focus();
	}

	return true;
}

/** Kind of a hack to get forms submitting in a new window */
function SubmitFormNewWindow( formname, url, name, width, height )
{
	var form = document.getElementById( 'ssearch' );
	
	if ( !form && form.elements.length <= 0 )
		return false;

	features = 'scrollbars=1,status=1,resizable=1' + ((width) ? ',width=' + width  : '') + ((height) ? ',height=' + height : '');


	newWindow = window.open( '', '_blank', features );
	// Now focusing the new window makes it go haywire!
	if ( newWindow.focus )
	{
		newWindow.focus();
	}

	newWindow.document.writeln( 
		"<html><head><title>Test Filter</title></head><body bgcolor='white' onLoad='self.focus()'>"
		+"	<form name='"+form.name+"' action='"+url+"' method='post' onSubmit=''>" );
	
	for ( var i = 0; i < form.elements.length; i++ )
	{
		newWindow.document.writeln( "<input type='hidden' name='"+form.elements[i].name+"' value='"+form.elements[i].value+"' />\n" );
	}

	//newWindow.document.writeln( "</form></body></html>" );*/
	/*newWindow.document.close();
	//newWindow.document.forms[0].submit();

	return false;*/

}