var objectToSave;


setEventQP(window, "load",processLoadQP);

var g_toolbarActionsQP = createToolbarActionsQP();

/* Initial Load Functions */

function processLoadQP()
{
	// Init OnScreen Divs
	var divs = getOnScreenDivCollectionQP()
	for (var i = 0; i < divs.length; i++) {
		initContainerQP(divs[i]);
	}
	
	//Init Toolbars and Buttons
	var buttons = getToolbarButtonsCollectionQP();
	for (var j = 0; j < buttons.length; j++) {
		initToolbarButtonQP(buttons[j]);
	}
	
	//Init whole Window (FF Only)
	if (!qp_isIE) {
		setEventQP(window, "click", winClick);
		setEventQP(window, "mousemove", winMouseMove);
		/*for (var i = 0; i < window.top.length; i++) {
			setEventQP(window.top[i], "click", winClick);
		}*/

	}
}

function initToolbarButtonQP(button) {
	var toolbar = getParentElementByAttrQP(button, "on_fly_type", "onfly_toolbar");
	button.toolbar = toolbar;
	attachButtonEventsQP(button);
}

function attachButtonEventsQP(button) {
	if (!qp_isIE || button.toolbar.onScreenDiv.contentEditable != "true") 
		setEventQP(button, "click", btnClick);
	setEventQP(button, "mouseover", btnMouseOver); // ????
	setEventQP(button, "mouseout", btnMouseOut);
}

function initContainerQP(div) {
	blockElemOuterCss(div);
	blockElemOuterCss(div.parentNode);
	
	attachEventsQP(div);
	copyAttributesQP(div);
	initBordersQP(div);
	
	div.focused = false;
	div.selection = null;
	div.originalContent = div.innerHTML;
	
	initToolbarQP(div);

	if(!qp_isIE && div.contentEditable == "true") { 
		div.editor = getElemQP(getIframeNameQP(div.onfly_no));
		div.editor.onScreenDiv = div;
		attachIframeEventsQP(div.editor);
		if (!qp_isIE) blockElemOuterCss(div.editor, true);
	}

}

function initToolbarQP(div) {
	var toolbar = getElemQP(getToolbarNameQP(div.onfly_no));
	div.toolbar = toolbar; 
	attachToolbarEventsQP(toolbar);
	toolbar.onScreenDiv = div;
	blockToolbarOuterCss(toolbar);
}

function attachEventsQP(div) {
	setEventQP(div, "click", DoFocus);
	setEventQP(div, "focus", DoFocus); // ????
	setEventQP(div, "mouseover", DoMouseOver);
	setEventQP(div, "mouseout", DoMouseOut);
	if (qp_isIE) {
		setEventQP(div, "beforedeactivate", DoBeforeDeactivate);
	}
	//setEventQP(div, "resize", DoResize); //SetBtnPos
}

function attachIframeEventsQP(editor) {
	setEventQP(editor.contentWindow, "blur", editorBlur);
	setEventQP(editor.contentWindow.document, "overflow", editorOverflow);
}

function copyAttributesQP(obj)
{
	obj.onfly_no = obj.getAttribute("onfly_no");
	obj.hicolor = obj.getAttribute("hicolor");
	obj.originalContent = obj.getAttribute("originalContent");
	obj.item_id = obj.getAttribute("item_id");
	obj.attribute_name = obj.getAttribute("attribute_name");
	obj.editable = obj.getAttribute("editable");
	obj.attr_required = obj.getAttribute("attr_required");
	obj.static_border = obj.getAttribute("static_border");
	obj.upload_url = obj.getAttribute("upload_url");
	obj.site_url = obj.getAttribute("site_url");
	obj.site_id = obj.getAttribute("site_id");
	obj.content_id = obj.getAttribute("content_id");	
	obj.is_dotnet = obj.getAttribute("is_dotnet");
	obj.contentEditable = obj.getAttribute("contentEditable");
}

function attachToolbarEventsQP(toolbar) {
	setEventQP(toolbar, "mouseout", btnMouseOut);
}


/* Border functions */

function setBorderQP(div) {
	if (div.static_border != "none") {
		if (qp_isIE || !(div.editor) || div.editor.style.display == "none") {
			div.style.padding = "0px";
			div.style.border = "2px dashed " + div.hicolor;
		}
	}
}

function resetBorderQP(div, preservePadding) {
	if (!preservePadding)
		div.style.padding = "2px";
	div.style.border = "none";
}

function initBordersQP(obj)
{
	if (obj.contentEditable == "true") { 
		if (obj.static_border == "true")
			setBorderQP(obj);
		else
			resetBorderQP(obj);
	}
}

/* Remote Scripting functions */

function endEdit(div) {
	if (qp_isIE)
		div.blur();
	else {
		hideToolbarQP(div.toolbar);
	}
}

function cancelQP(div) {
	rejectLiveContentQP(div);
	endEdit(div);
}


function saveQP(obj, isConfirmed) {
	var htmlToSave = getLiveContentQP(obj);
	if ((htmlToSave == "") && (obj.attr_required == 1))  {
		alert("Field is required. Empty value is not valid!");
		return;
	}

	if (isConfirmed || confirm("Save changes?")) {
		var asp_obj = (obj.is_dotnet == 1) ? RSGetASPObject(decodeURIComponent(g_siteUrl) + "MyFly.aspx") : RSGetASPObject(decodeURIComponent(g_siteUrl) + "onfly.asp");
	
		var decreaseStatus = asp_obj.DecreaseStatus(obj.item_id).return_value;
		if (decreaseStatus != 0) {
	 		if (!confirm(decreaseStatus)) return;
		}
		msrsPOST = true;
		objectToSave = obj;
		asp_obj.UpdateArticle(obj.item_id, obj.attribute_name, g_uploadUrl, g_siteUrl, htmlToSave, updateCallbackQP, updateCallbackQP);
	}
}


function updateCallbackQP(call_obj){
	msrsPOST = false;
	var obj = objectToSave;
	var call_result = "" + call_obj.return_value;
	var call_result = call_result.split("|");
	if (call_result[0] == 1) {
		applyLiveContentQP(obj);
		endEdit(obj);
/*		var div;
		for (var i = 1; window.document.all["onfly_div_" + i]; i++) {
			div = eval("onfly_div_" + i);
			if ((div.item_id == item_id) && (div.attribute_name == attribute_name)) {
				div.innerHTML = innerHTML;
				div.originalContent = innerHTML;
			}
		}
*/
		if (call_result.length > 1) 
			alert(call_result[1]);
	} else {
		rejectLiveContentQP(obj);
		alert(call_obj.return_value + "\nResult: " + call_obj.status + "\n" + call_obj.message);
	}
}

function createLikeQP(obj) {
	var asp_obj = (obj.is_dotnet == 1) ? RSGetASPObject(decodeURIComponent(g_siteUrl) + "MyFly.aspx") : RSGetASPObject(decodeURIComponent(g_siteUrl) + "onfly.asp");
	var newId;

	var result = asp_obj.CreateLikeArticle(obj.item_id, obj.content_id, obj.site_id).return_value;
	var results = result.split("|");
	var resultCode = results[0];

	if (resultCode == 1) 
		newId = results[1];
	else 
		alert(results[1]);
	return newId;
}


/* Name functions */

function getToolbarNameQP(number) {
	return "onfly_toolbar_" + number;
}

function getButtonTdNameQP(shortName, number) {
	return "onfly_" + shortName + "_btn_" + number;
}

function getButtonNameQP(shortName, number) {
	return "onfly_" + shortName + "_btn_img_" + number;
}

function getButtonShortNameQP(name) {
	var result = name;
	result = result.replace("onfly_", "");
	result = result.replace("_btn_", "");
	result = result.replace("img_", "");
	var re = /[\d]+/g;
	result = result.replace(re, "");
	return result;
}

function getPictureNameQP(shortName, number) {
	return "onfly_" + shortName;
}

function getHrefNameQP(shortName, number) {
	return "onfly_href_" + shortName + "_" + number;
}

function getIframeNameQP(number) {
	return "onfly_iframe_" + number;
}


/* Toolbar functions */

function getMaxZIndex() {
	return 10000;
}

function makeTop(toolbar) {
	var container = toolbar.onScreenDiv.parentNode;
	toolbar.style.zIndex = getMaxZIndex();
	container.style.zIndex = getMaxZIndex();
}

function restoreStackPosition(toolbar) {
	var container = toolbar.onScreenDiv.parentNode;
	container.style.zIndex = 0;
}

function showToolbarQP(toolbar) {
	var div = toolbar.onScreenDiv;
	var number = div.onfly_no;
	if (top.frames["main"]) {
		showElemQP(getButtonTdNameQP("go_info", number));
		showElemQP(getButtonTdNameQP("go_new", number));
		showElemQP(getButtonTdNameQP("create_like", number));

		makeTop(toolbar);

		showElemQP(toolbar.id);

		toolbar.style.width = getLiveToolbarWidth(toolbar); //

		if (!qp_isIE && div.contentEditable == "true") { 
			showIframeEditorQP(div);
			resetBorderQP(div, true);
		}

		if (WCH) 
			WCH.Apply(toolbar.id);
	}
}

function hideToolbarQP(toolbar) {
	
	hideElemQP(toolbar.id);
	
	restoreStackPosition(toolbar);
	
	var div = toolbar.onScreenDiv;
	if (!qp_isIE && div.contentEditable == "true") {
		hideIframeEditorQP(div);
		if (div.static_border == "true") 
			setBorderQP(div);
	}
	if (WCH) 
		WCH.Discard(toolbar.id);

}

function goHrefQP(href, div, frameName) {
	if (qp_isIE) {
		var hrefObj = document.createElement("a");
		hrefObj.href = href;
		hrefObj.target = frameName; 
		div.toolbar.appendChild(hrefObj);
		hrefObj.click();
	} else {
		var goForm = document.createElement("form");
		div.toolbar.appendChild(goForm);
		goForm.target = frameName;
		goForm.action = href;
		goForm.method = "POST";
		goForm.submit();
	}
}

function getCommonArticleHref(tabName, contentId, contentItemId) {
	var codedTabName = tabName.replace(" ", "+");
	var href = g_backendUrl + "?redirect=" + codedTabName + "&content_id=" + contentId + "&content_item_id=" + contentItemId + "&ret_stage_url=" + g_returnStageUrl;
	return href;
}

function getCreateLikeHref(div, id) {
	return getCommonArticleHref("Article Info", div.content_id, id);
}

function getNewArticleHref(div) {
	return getCommonArticleHref("New Article", div.content_id, 0);
}

function getEditArticleHref(div) {
	return getCommonArticleHref("Article Info", div.content_id, div.item_id);
}

function getLiveToolbarWidth(toolbar) {
	var cells = toolbar.getElementsByTagName("td");
	var result = 0;
	for (var i = 0; i < cells.length; i++) {
		var isButton = cells[i].getAttribute("on_fly_type");
		result += (isButton) ? 28 : 14;
	}
	return result + "px";
}

function blockToolbarOuterCss(toolbar) {
	blockElemOuterCss(toolbar, true)
	blockToolbarChildOuterCss(toolbar, "table");
	blockToolbarChildOuterCss(toolbar, "tr");
	blockToolbarChildOuterCss(toolbar, "td");
	blockToolbarChildOuterCss(toolbar, "img");
}

function blockToolbarChildOuterCss(toolbar, tagName)
{
	var children = toolbar.getElementsByTagName(tagName);
	for(var i = 0; i < children.length; i++) {
		blockElemOuterCss(children[i]);
	} 
}

function blockElemOuterCss(elem, preserveBorder) {
	if (elem) {
		elem.style.padding = "0px";
		elem.style.margin = "0px"
		if (!preserveBorder) 
			elem.style.border = "none";
	}
}


/* Collection functions */

function getOnScreenDivCollectionQP() {
	if (!window.onFlyDivs) window.onFlyDivs = getElementsByAttrQP("div", "on_fly_type", "onfly_div");
	return window.onFlyDivs;
}

function getToolbarButtonsCollectionQP() {
	return getElementsByAttrQP("img", "on_fly_type", "onfly_toolbar_btn");
}

/* Toolbar action functions */

function addActionQP(name, type, justifyName, loseFocus) {
	var obj = new Object;
	obj.type = type;
	obj.justifyName = justifyName;
	obj.loseFocus = loseFocus;
	this[name] = obj;
}
function createToolbarActionsQP() {
	var obj = new Object();
	obj.addAction = addActionQP;
	obj.addAction("cancel", "action", "", true);
	obj.addAction("save", "action", "", true);
	obj.addAction("go_info", "href");
	obj.addAction("go_new", "href");
	obj.addAction("create_like", "action");
	obj.addAction("bold", "command");
	obj.addAction("italic", "command");
	obj.addAction("underline", "command");
	obj.addAction("center", "command", "justifycenter");
	obj.addAction("justify", "command", "justifyfull");
	obj.addAction("right", "command", "justifyright");
	obj.addAction("left", "command", "justifyleft");
	return obj;
}

function isActionQP(obj) {
	var result = false;
	if (obj && obj.id) {
		var shortName = getButtonShortNameQP(obj.id);
		if (shortName && g_toolbarActionsQP[shortName]) 
		result = true;
	}
	return result;
}

function processActionQP(button, customEvent, div){
	var shortName = getButtonShortNameQP(button.id);
	var action = g_toolbarActionsQP[shortName];
	if (action) {
		if (action.type == "command") {
			var commandName = (action.justifyName) ? action.justifyName : shortName;
			execCommandQP(div, commandName);  
		} else {
			switch(shortName) {
				case "save": {
					saveQP(div, false);
					break;
				}
				case "cancel": {
					cancelQP(div);
					break;
				}
				case "create_like": {
					var newId = createLikeQP(div);
					if (newId) {
						var href = getCreateLikeHref(div, newId);
						goHrefQP(href, div, "main")
					}
					break;
				}
				case "go_new" : {
					var href = getNewArticleHref(div);
					goHrefQP(href, div, "main");
					break;
				}
				case "go_info" : {
					var href = getEditArticleHref(div);
					goHrefQP(href, div, "main");
					break;
				}
			
			}
			if (action.loseFocus)
				loseFocusQP(div);
		}
			
	}
	stopEventQP(customEvent, false);
}


/* Visual Editor functions */

function getSelectionQP(obj) {
  var oSel = document.selection.createRange();
  oSel.type = document.selection.type;
  return oSel;
}

function execCommandQP(obj, commandName) {
  if (qp_isIE) {
	  var oSel = getSelectionQP(obj);
	  if (oSel.type != "None")
	  	oSel.execCommand(commandName, false);
  } else {
		obj.editor.contentWindow.document.execCommand(commandName, false, null);
	}
}

function loseFocusQP(obj) {
	obj.focused = false;
	hideToolbarQP(obj.toolbar);
	if (obj.static_border != "true") {
		resetBorderQP(obj);
	}
}


/* Mozilla-specific Visual editor functions */

function copyStylesQP(source, destination, styles) {
	for (var i = 0; i < styles.length; i++) {
		var styleName = styles[i];
		destination[styleName] = source[styleName];
	}
}
	
function copyParentCssQP(editor) {
	var editorWin = editor.contentWindow;
	var editorDoc = editorWin.document;
	var editorCss = editorDoc.getElementById("editor_css");

	if (editorCss){
		return;   
    }
	else {
	    /*********************************************************** 
	    ****** currently taken out since it may break styling ******	    
	    ****** copying css stylesheets                        ******
	    ************************************************************
	    */
	    
	    /*
		var editorHead = editorDoc.getElementsByTagName("head")[0];
		var editorCSS = editorDoc.createElement("style");		        
        editorCSS.setAttribute("id", "editor_css");
        editorHead.appendChild(editorCSS);
        
		if (document.styleSheets.length > 0) {
	        for (var i = 0; i < document.styleSheets.length; i++) {
	        	        
	            var cssRules = document.styleSheets[i].cssRules;
	            var counter = 0;
			    for (var j = 0; j < cssRules.length; j++) {			
				    editorCSS.sheet.insertRule(cssRules[j].cssText, counter);
				    counter++;
			    }
	        }			
	    }
	    */
	   
		var compStyle = window.getComputedStyle(editor.onScreenDiv, "");
		var editorStyle = editorDoc.body.style;
		var stylesToCopy = new Array("fontFamily", "fontStyle", "fontWeight", "fontSize", "color", "lineHeight","letterSpacing","wordSpacing","whiteSpace", "paddingLeft", "marginLeft", "paddingRight", "marginRight", "paddingTop", "marginTop", "paddingBottom", "marginBottom");
		copyStylesQP(compStyle, editorStyle, stylesToCopy)
		
	}
}

function showIframeEditorQP(div){
	var editor = div.editor;
	getOffsetQP(div);
	
	editor.style.width = div.offsetWidth + "px";
	editor.style.height = div.offsetHeight + "px";
	
	var editorDoc = editor.contentWindow.document;

	copyParentCssQP(editor);
	
	
	var editorBody = editorDoc.getElementsByTagName("body")[0];
	var clone = div.cloneNode(true)
	clone.editor = null;
			
    editorBody.innerHTML = "";		
	if (div.innerHTML){
	    var length = clone.childNodes.length;
        for(var s=0;s<length; s++){
           editorBody.appendChild(clone.childNodes[0]);    
        }		
	}
			
	showElemQP(editor.id);
	editor.contentDocument.designMode = "on";
	
	editor.contentWindow.focus();
	
	editor.contentWindow.document.onflyDiv = div;
	
	//div.style.width = div.clientWidth;
	//div.style.height = div.clientHeight;
	
	div.innerHTML = "";
	//correctToolbarPositionQP(div.toolbar);

}

function hideIframeEditorQP(div) {
	var editor = div.editor;
	var editorDoc = editor.contentWindow.document;
	if (editorDoc.body.innerHTML) 
		div.innerHTML = editorDoc.body.innerHTML;
	else 
		div.innerHTML = div.originalContent;
	
	div.style.width = "";
	div.style.height = "";
	hideElemQP(editor.id);
}

function getLiveContentQP(div) {
	var result = (qp_isIE) ? div.innerHTML : getEditorContentQP(div.editor);
	return result;
}

function rejectLiveContentQP(div) {
	div.innerHTML = div.originalContent;
	if(!qp_isIE) {
		clearEditorContentQP(div.editor);
	}	
}

function applyLiveContentQP(div) {
	if (!qp_isIE) {
		div.innerHTML = getEditorContentQP(div.editor);
		clearEditorContentQP(div.editor);
	}
	div.originalContent = div.innerHTML
}

function setEditorContentQP(editor, html) {
	editor.contentWindow.document.body.innerHTML = html;
}

function getEditorContentQP(editor) {
	return editor.contentWindow.document.body.innerHTML;
}

function clearEditorContentQP(editor) {
	editor.contentWindow.document.body.innerHTML = "";
}

