/*
 * Javascript functions specific for adaptive package pages,
 * setupPackage.jsp and adminPackage.jsp.
 *
 * @author Bokedal, Calle (cabo02)
 *
 * Change History <br>
 * Date       Author Comment <br>
 * ---------- ------ ---------------------------------------------- <br>
 * 2005-04-01 cabo02 Initial version.
 * 2005-05-12 cabo02 Added doSubmit variable.
 * 2005-06-08 cabo02 Removed obsolete code and updated update function.
 * 2005-06-16 cabo02 Removed undefined check to get script to work on old browsers.
 *                   NOTE! Previous impl. check was supported by ECMA-262.
 * 2005-09-12 cabo02 Renamed form element "method" to "command" to prevent Safari bug.
 * 2006-09-13 cabo02 Created handleMobileTermsUpdate(...)
 * 2008-12-22 beho04 Closing detailed descriptions when 'Dölj alternativ' is clicked
 * 2009-01-08 beho04 Moved javascript from orderFlowScripts to this file.
 * 2009-12-15 magu93 Updated handling of mobile terms
 *                   Removed showLayer(), hideLayer() and doUpdateAjax()
 * 2010-02-25 dagr09 Imported doUpdateCutAndPasteAjax from the jsp-pages
 */

/**
 * Functions below are to be considered as legacy and deprecated.
 * Search 'howto' on the wiki for more info.
 */



/*
 *  Note, comment below is from the .jsp-page
 *  It does no longer override.  doUpdate now calls it instead.
 */
/*
 * This method overrides the doUpdate() in include/scripts/adaptivePackageScripts.js and makes the same POST but as an AJAX request.
 * The response of the post (which is an entire html response) is parsed, and the content between  the "AJAX UPDATE BEGIN" and "AJAX UPDATE END" html-comments 
 * is pasted to replace the entire form tag content of the adaptive flows current step.
 * 
 * If an error occures, the script falls back to posting the html-form as usual.
 * 
 * This script is dependant on:	
 * - prototype 1.5.1+
 * - orderFlowTimeout.js
*/

function doUpdateCutAndPasteAjax(formElem, anchor) {
	formElem.form.command.value = 'update';
	var actionTarget = formElem.form.action;
	var formElement = formElem;
	var formElementTabIdx = $(formElem).readAttribute("tabindex");
	var buttonHref = "";
	var buttonNext = dojo.query('button#buttonNext');
	var btnPrevious = dojo.query('button.btnPrevious');
	if(buttonNext[0] != null && btnPrevious[0] != null && document.forms["adaptiveForm"].jspstate.value.startsWith("optionsInclude")) {
		dojo.empty(buttonNext[0]);
		dojo.place("<button onclick='return false;' class='right tsButtonSpringGreen29 tsButtonDisable29'><span><span>Nästa</span></span></button>", btnPrevious[0], "after");
	}
	if(btnPrevious != null){
		btnPrevious.addClass("tsButtonDisable29");
		btnPrevious.attr("onClick", "return false;");
	}
	var tsLoadingIcon = dojo.query('img#tsLoadingIcon');
	if(tsLoadingIcon != null && document.forms["adaptiveForm"].jspstate.value.startsWith("optionsInclude")){
		tsLoadingIcon.addClass("tsLoadingIconIE");
		dojo.style(tsLoadingIcon[0], "position", "absolute");
		dojo.style(tsLoadingIcon[0], "display", "block");
	}
	var ajaxRequest = new Ajax.Request(actionTarget, {
		method : 'post',
		parameters : $(document.forms["adaptiveForm"]).serialize(true),
		onCreate : function() {
			// Disable the form to keep the user from making multiple requests
			// when waiting for a response
		    $(document.forms["adaptiveForm"]).disable();
		// Also disable btnNext, because otherwise we can get strange behaviour
		// where we replace the form at the same time as we are posting it..
		// Save existing href for button
		buttonHref = $('buttonNext').href;
		// replace with a dummy action
		$('buttonNext').href = "javascript:";

		// If we have a session timer object, call it's reset method
		if (sessionTimer)
			sessionTimer.reset(false);
	},
	onComplete : function(transport) {

		var response = transport.responseText || "no response text";
		// Get range to cut/paste
		var start = response.indexOf("<!" + "-- AJAX UPDATE BEGIN -->");
		var end = response.indexOf("<!" + "-- AJAX UPDATE END -->");
		if (start > 0) {
			// Get the actual content to paste
			var fragment = response.substring(start, end);
			if(window.location.hash.charAt(10) >= 0){
				fragment = fragment.replace('<div class="sys12Grid9 omega alpha" id="tsOptionBox">', '<div class="sys12Grid9 omega alpha" id="tsOptionBox" style="display:block">');
				fragment = fragment.replace('<div class="tsAdaptiveProductBlock" id="' + window.location.hash.charAt(10) + '">', '<div class="tsAdaptiveProductBlock" id="' + window.location.hash.charAt(10) + '" style="display: block">');
				fragment = updateCart(fragment);

			}
			// Finally, do the actual content switch!
			if(document.getElementById("adaptiveOrderFlowContainerOpen") != null){
			    // Foretag
			    $('adaptiveOrderFlowContainerOpen').replace(fragment);
			    document.getElementById("adaptiveOrderFlowContainerOpen").style.display = "block";
			} else {
			    $(document.forms["adaptiveForm"]).replace(fragment);
			}
		}
		// Rebind events to form
		bindEventListenersToForm();

		// And re-enable the next button
		$('buttonNext').href = buttonHref;

		// Focus input that triggered event
		$(document.forms["adaptiveForm"]).select(
				'[tabindex="' + formElementTabIdx + '"]').first().focus();
	},
	onFailure : function() {
		// Fallback to normal post to show any error to user.
		// alert("onFailure");
		$(document.forms["adaptiveForm"]).submit();
	}
	});
}


/**
 * "Public" function to handle pagebuttons
 * @param {Form} formElem Form element to submit
 * @param {String} anchor Anchor to send along
 */
function doUpdate(formElem, anchor) {
    if(document.forms["adaptiveForm"].jspstate.value.startsWith("setupPackage") || document.forms["adaptiveForm"].jspstate.value.startsWith("optionsInclude") || document.forms["adaptiveForm"].jspstate.value.startsWith("hardwareInclude")){
    	doUpdateCutAndPasteAjax(formElem, anchor);
    }else{
        formElem.form.command.value = 'update';
        formElem.form.action = formElem.form.action + "#" + anchor;
        formElem.form.submit();
    }
}

function doUpdateProductContentBlock(element){
	var formElem = dojo.query(element).parent().parent().children("label").children("input");
	if(formElem.attr("type")[0] == "radio"){ 
		formElem.attr("checked", "checked"); 
	} else {
		if(formElem.attr("checked")[0] == true) {
			formElem.removeAttr("checked");
		} else {
			formElem.attr("checked", "checked");
		}
	}
	var startPos = formElem.attr("id").toString();
	startPos = startPos.replace("item", "anchor_");
	doUpdate(formElem[0], startPos);
}

function doUpdateImageBlock(element){
	var formElem = dojo.query(element).parent().children("input");
	if(formElem.attr("type")[0] == "radio"){ 
		formElem.attr("checked", "checked"); 
	} else {
		if(formElem.attr("checked")[0] == true) {
			formElem.removeAttr("checked");
		} else {
			formElem.attr("checked", "checked");
		}
	}
	var startPos = formElem.attr("id").toString();
	startPos = startPos.replace("item", "anchor_");
	doUpdate(formElem[0], startPos);
}

/**
 * "Public" function to handle mobile terms change 
 */
function handleMobileTermsUpdate(formElem, index) {
	var item = 'package_mobile_engagement_price_select_' + index;
	$(item).value = formElem.value;
	var anchor = 'anchor_handleMobileTermsUpdate_' + index;
	doUpdate(formElem, anchor);
}

function handleServiceTiePeriodUpdate(formElem, index) {
	var item = 'package_optional_tieperiod_select_' + index;
	$(item).value = formElem.value;
	var anchor = "anchor_handleTiePeriodUpdate_" + index;
	doUpdate(formElem, anchor);
}

/**
 * "Public" function to handle mobile terms month value change 
 */
function handleMobileTermsTiePeriodUpdate(formElem, index) {
	var item = 'package_mobile_engagement_tieperiod_select_' + index;
	$(item).value = formElem.value;
	var anchor = "anchor_handleMobileTermsUpdate_" + index;
	doUpdate(formElem, anchor);
}

/**
 * "Public" function to handle mobile mobilpeng month value change 
 */
function handleMobileMobilpengUpdate(formElem, index) {
	var item = 'package_mobile_engagement_mobilpeng_select_' + index;
	$(item).value = formElem.value;
	var anchor = "anchor_handleMobilpengUpdate_" + index; 
	doUpdate(formElem, anchor);
}

function toggleGroup(id, imgTag) {
        var rows = $$('tr.group'+id);
        for(var i=0; i<rows.length; i++){
                Element.toggle(rows[i]);
        }
        if (document.forms["adaptiveForm"].elements["contractPackage.groupMap(" + id + ").expanded"].value == 'true') {
                document.forms["adaptiveForm"].elements["contractPackage.groupMap(" + id + ").expanded"].value = false;
                imgTag.src='/img/buttons/button_visaalternativ.gif';
                imgTag.title='Visa alternativ';

                /* Hide all detail rows */
                var detailRows = $$('tr.detailsForGroup'+id);
                for(var i=0; i<detailRows.length; i++){
                        Element.hide(detailRows[i]);
                }

                /* Reset hide and show buttons. */
                var hideShowButtons = $$('img.hideShowButtonForGroup'+id);
                for(var i=0; i<hideShowButtons.length; i++){
                        hideShowButtons[i].src = "/img/buttons/info.png";
                        hideShowButtons[i].title = "Visa info";
                }
        } else {
                document.forms["adaptiveForm"].elements["contractPackage.groupMap(" + id + ").expanded"].value = true;
                imgTag.src='/img/buttons/button_doljalternativ.gif';
                imgTag.title='Dölj alternativ';
        }
}

/*
 * showHideInfo (for telia privat)
 */
function showHideInfo(infoIdName) {
        _showHideInfo(infoIdName, '/img/buttons/info.png','/img/buttons/info_selected.png', false);
}

/*
* showHideInfoCompany (for telia foretag)
*/
function showHideInfoCompany(infoIdName) {
        _showHideInfo(infoIdName, '/include/foretag/graphics/adaptiveFlowMoreInfo.gif' ,'/include/foretag/graphics/adaptiveFlowCloseMoreInfo.gif', true);
}

/*
* Internal function
*/
function _showHideInfo(infoIdName, moreButtonSrc, closeButtonSrc, isForetag) {

        var infoField = document.getElementById(infoIdName);

        if (infoField.style.display == "none"){
                infoField.style.display = "";
                var infoField_img = infoIdName + "_img";
                var infoImage = document.getElementById(infoField_img);
                infoImage.src = closeButtonSrc;
                infoImage.title = "Dölj info";

                if (isForetag) {
                        var lineId = infoIdName + "_line";
                        var infoLineElement = document.getElementById(lineId);
                        infoLineElement.style.display = "";
                }
        } else {
                infoField.style.display = "none";
                var infoField_img = infoIdName + "_img";
                var infoImage = document.getElementById(infoField_img);
                infoImage.src = moreButtonSrc;
                infoImage.title = "Visa info";

                if (isForetag) {
                        var lineId = infoIdName + "_line";
                        var infoLineElement = document.getElementById(lineId);
                        infoLineElement.style.display = "none";
                }
        }
}

/*
	New Functions
*/

dojo.require("dojo.NodeList-traverse");
dojo.require("dojo.NodeList-manipulate");
dojo.require('dojox.timing');
dojo.require("dojo.fx.easing");

function updateCart(arg){
	var tmpVar = arg;

	tmpVar = tsSearchAndReplace(tmpVar, '<div class="sys12Grid3 omega alpha right" id="tsTabLeft" style="display: none">', '<div class="sys12Grid3 omega alpha right" id="tsTabLeft" style="display: block;">');

	var tsIdList = new Array();

	dojo.forEach(dojo.query("#tsOptionBox .tsAdaptiveProductBlock .tsPBoxes input:checked"), function(entry, i){
		var id = dojo.attr(dojo.query(entry).parent().parent().parent().parent()[0], "id");
		tsIdList.push(id);
	});

	dojo.forEach(dojo.query("#tsOptionBox .tsAdaptiveProductBlock"), function(entry, i){
		var id = dojo.query(entry).attr("id")[0];
		if(!tsContains(id, tsIdList)){
			tmpVar = tsSearchAndReplace(tmpVar, '<p class="tsDisplayNoChoiceText" id="tsDisplayNoChoiceText' + id +'" style="display:none">', '<p class="tsDisplayNoChoiceText" id="tsDisplayNoChoiceText' + id +'" style="display:block">');
		} 
	});

	dojo.forEach(dojo.query("#tsOptionBox .tsAdaptiveProductBlock input:checked"), function(entry, i){
		var id = dojo.attr(dojo.query(entry).parent().parent().parent().parent()[0], "id");
		var tsStringCheck = tmpVar.substring(tmpVar.indexOf(dojo.query(entry).attr("id")) - 150, tmpVar.indexOf(dojo.query(entry).attr("id")) + 10);
		if(tsStringCheck.indexOf('disabled="disabled"') > 0) {
			tmpVar = tsSearchAndReplace(tmpVar, '<p class="tsDisplayNoChoiceText" id="tsDisplayNoChoiceText' + id +'" style="display:none">', '<p class="tsDisplayNoChoiceText" id="tsDisplayNoChoiceText' + id +'" style="display:block">');
		} else {
			tmpVar = tsSearchAndReplace(tmpVar, '<p style="display:none" id="tsProduct' + id + dojo.attr(entry, "value") +'">', '<p style="display:block" id="tsProduct' + id + dojo.attr(entry, "value") +'">');
		}
	});

	return tmpVar;

}

function tsContains(arg, list){
	for(i = 0; i < list.size(); i++){		
		if(arg == list[i]){
			return true;
		}
	}
	return false;
}


function tsSearchAndReplace(varOne, varTwo, varThree){

	var tmpVar = varOne;

	tmpVar = tmpVar.replace(varTwo, varThree);

	return tmpVar;	
}

function tsShowProductBox(arg){
	dojo.forEach(dojo.query("div.tsAdaptiveProductBlock"), function(entry, i){
		dojo.style(entry, "display", "none");
	});
	tsHideTabContainer();
	tsLoading(arg)
}

function tsOrderStartButton(arg){
	dojo.forEach(dojo.query("div.tsAdaptiveProductBlock"), function(entry, i){
		dojo.style(entry, "display", "none");
	});
	tsHideTabContainer();
	tsLoading(arg);
	if(document.forms["adaptiveForm"].jspstate.value.startsWith("setupPackage")) {
		dojo.style("flowIndicator", "display", "block");
	}
}

function tsLoading(arg){
	t = new dojox.timing.Timer(1250);
	t.onTick = function() {
		dojo.query("#tsLoadingIcon").style("display", "none");
		setSelectedTab(arg);		
		dojo.query("div#" + arg + ".tsAdaptiveProductBlock").style("display", "block");
		dojo.query("#tsOptionBox").style("display", "block");
		t.stop();
	}
	t.onStart = function() {
		dojo.query("#tsProductTab").style("display", "none");
		dojo.query("#tsLoadingIcon").style("display", "block");
	}
	t.start();
}

function tsHideTabContainer(){
	dojo.query("#tsTabLeft div a button").style("display", "none");
	dojo.query("#tsProductInfo").style("display", "none");
	dojo.query("#tabContainer").style("display", "none");
	dojo.query("#tabContentLeft").style("display", "none");
}

function tsOnStart(){
	dojo.query("#tsTabLeft div a button").style("display", "block");
	dojo.query("#tsProductInfo").style("display", "block");
	dojo.query("#tabContainer").style("display", "block");
	dojo.query("#tabContentLeft").style("display", "block");
}


function tsDisplayNoChoiceText(){

	var tsIdList = new Array()

	dojo.forEach(dojo.query("#tsOptionBox .tsAdaptiveProductBlock .tsPBoxes input:checked"), function(entry, i){
		var id = dojo.attr(dojo.query(entry).parent().parent().parent().parent()[0], "id");
		tsIdList.push(id);
	});

	dojo.forEach(dojo.query("#tsOptionBox .tsAdaptiveProductBlock"), function(entry, i){
		var id = dojo.query(entry).attr("id")[0];
		if(!tsContains(id, tsIdList)){
			dojo.query("#tsDisplayNoChoiceText" + id).style("display", "block");
		}
	});
}

function tsInitCart(){

	tsDisplayNoChoiceText();

	if(document.forms["adaptiveForm"].jspstate.value.startsWith("setupPackage")) {
		dojo.query("#tsTabLeft").style("margin", "0px");
	}

	dojo.forEach(dojo.query("#tsOptionBox .tsAdaptiveProductBlock input:checked"), function(entry, i){
		var id = dojo.attr(dojo.query(entry).parent().parent().parent().parent()[0], "id");

		dojo.query("#tsCart span#tsCategory" + id + ".tsCategory").style("display", "block");
		dojo.query("#tsCart p#tsProduct" + id + dojo.attr(entry, "value")).style("display", "block");
	});
}



function setSelectedTab(arg){
	dojo.forEach(dojo.query("ul#tsTab span"), function(entry, i){
		if(i == arg){
			dojo.query(entry).addClass("tsTabSelected");
			dojo.query(entry).children("a").attr("onClick", "return false");
		} else {
			dojo.query(entry).removeClass("tsTabSelected");
			dojo.query(entry).children("a").attr("onClick", "tsShowProductBox('" + i + "');");
		}
	});

	if(document.forms["adaptiveForm"].jspstate.value.startsWith("setupPackage")) {
		tsDisplayProductTab();	
	}
}

function tsDisplayProductTab(){
	dojo.query("#tsTabLeft").style("margin", "64px 0 0");
	dojo.query("ul#tsTab").style("display", "block");
	dojo.query("#flowIndicator").style("display", "block");
}

function tsShowInfo(arg){

	document.getElementById(arg).style.height = "auto";

	if(dojo.query("#" + arg + "link").attr("title") == "Visa info")
	{
		dojo.animateProperty({
			node: arg,
			onEnd: function(node){
				dojo.query("#" + arg + "link").addClass("tsInfoLinkSelected");
				dojo.query("#" + arg + "link")[0].blur();
				dojo.query("#" + arg + "link").attr("innerHTML", "Dölj info");
				dojo.query("#" + arg + "link").attr("title", "Dölj info");
			},
			properties:{
				height: { end: document.getElementById(arg).offsetHeight, start: "0" },
				unit: "px"
			},
			easing: dojo.fx.easing.linear
		}).play();
	} else {
		dojo.animateProperty({
			node: arg,
			onEnd: function(node){
				dojo.query("#" + arg + "link").removeClass("tsInfoLinkSelected");
				dojo.query("#" + arg + "link")[0].blur();
				dojo.query("#" + arg + "link").attr("innerHTML", "Visa info");
				dojo.query("#" + arg + "link").attr("title", "Visa info");
			},
			properties:{
				height: { end: "0" , start: document.getElementById(arg).offsetHeight },
				unit: "px"
			},
			easing: dojo.fx.easing.linear
		}).play();	
	}
}

function tsShowButton(arg){
	var node = dojo.query("div#" + arg + ".tsAdaptiveProductBlock");

	dojo.forEach(dojo.query("div.tsAdaptiveProductBlock"), function(entry, i){
		if(entry == node[0]){ 
			dojo.query("#tsTabLeft").style("top", "0px");
			tsLoading(arg);
		} else {
			dojo.style(entry, "display", "none");
		}
	});
}

function tsDisableSelectedIfZero(){
	dojo.forEach(dojo.query("select"), function(entry, i){
		if(dojo.query(entry).children().size() == 1){
			dojo.query(entry).attr("disabled", "true");
		}
	});

	dojo.forEach(dojo.query("div.tstsAdaptiveContentBlock"), function(entry, i){
		if(dojo.query(entry).children(".tsPBoxes").size() > 5){
			dojo.query(entry).next(".tsButtonBlockBottom").style("display", "block");
		}
	});
}


