
  /*
    Startup code , runs when page is loaded, setting clickevents 
   */

$(document).ready(function() {
    reinitialiseEvents();
});

function reinitialiseEvents() {


    $('.topLogin').click(function() {
        $('.topLogin').hide();
        $('.topLoginForm').slideDown('slow');
    });

    $('.closeLoginForm').click(function() {
        $('.topLogin').slideDown('slow');
        $('.topLoginForm').hide();
        $('.loginerrormessage').hide();
    });

    $('.addToMyBizbook, .alreadyInMyBizbook, .addContactToMyBizbook, .addCompanyToMyBizbook, .promoteMyBizbookDialog').mouseover(
            function() {
                $(this).find('.addToMyBizbookBox').css('display', 'block'); //fadeIn(100);
            }).mouseout(
            function() {
                $(this).find('.addToMyBizbookBox').css('display', 'none'); //.fadeOut(100);
            });

    $('.comparecompanies').mouseover(
            function() {
                $(this).find('.comparecompaniesbox').css('display', 'block'); //fadeIn(100);
            }).mouseout(
            function() {
                $(this).find('.comparecompaniesbox').css('display', 'none'); //.fadeOut(100);
            });

    $('.addCompanyToMyBizbook').click(function(){
        tb_show('', '#TB_inline?height=220&width=360&inlineId=addCompanyDialogId', false);
    });

    $('.promoteMyBizbookDialog').click(function(){
        tb_show('', '#TB_inline?height=220&width=360&inlineId=promoteMyBizbookDialogId', false);
    });

    $('.promoteStandardDialog').click(function(){
        tb_show('', '#TB_inline?height=220&amp;width=360&amp;inlineId=promoteStandardDialogId', false);
    });

    $('.promotePlusDialog').click(function(){
        tb_show('', '#TB_inline?height=220&amp;width=360&amp;inlineId=promotePlusDialogId', false);
    });

    $('.areyousuredialog').click(function(){
        tb_show('', '#TB_inline?height=480&amp;width=476&amp;inlineId=areYouSureDialogId', false);
    })

    $("input:checkbox.white").each(function() {
        $(this).css('display', 'none');
        (this.checked) ? $("#fakeWhite" + this.id).addClass('fakeWhitechecked') : $("#fakeWhite" + this.id).removeClass('fakeWhitechecked');
    });
    $("input:checkbox.grey").each(function() {
        $(this).css('display', 'none');
        (this.checked) ? $("#fake" + this.id).addClass('fakechecked') : $("#fake" + this.id).removeClass('fakechecked');
    });
    $(".fakeWhitecheck").click(function() {
        ($(this).hasClass('fakeWhitechecked')) ? $(this).removeClass('fakeWhitechecked') : $(this).addClass('fakeWhitechecked');
        $(this.hash).trigger("click");
        return false;
    });

    $(".fakecheck").click(function() {
        ($(this).hasClass('fakechecked')) ? $(this).removeClass('fakechecked') : $(this).addClass('fakechecked');
        $(this.hash).trigger("click");
        return false;
    });


    $('#morefinance-show').click(function() {
        $('#financemorebox').show('slow');
        $('a#morefinance-show').hide();
        $('a#morefinance-hide').show();
        $('div#minimaleconomy').hide();
        return false;
    });

    $('a#morefinance-hide').click(function() {
        $('a#morefinance-show').show();
        $('a#morefinance-hide').hide();
        $('#financemorebox').hide('slow');
        $('div#minimaleconomy').show();
        return false;
    });
    
    if($("#card").length > 0)
    	hideCardForm();
}

function setAddContactHandler() {
    $('.addContactToMyBizbook').click(function(){
        tb_show('', '#TB_inline?height=220&width=360&inlineId=addContactDialogId', false);
    });
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


function openPromoteStandardDialog(){
      tb_show('', '#TB_inline?height=250&amp;width=350&amp;inlineId=promoteStandardDialogId', false);
 }
function openPromotePlusDialog(){
      tb_show('', '#TB_inline?height=250&amp;width=350&amp;inlineId=promotePlusDialogId', false);
}
function isSubmit(node) {
	return node != null && node.nodeType == 1
		&& node.tagName.toLowerCase() == "input"
		&& node.getAttribute("type") == "submit";
}

function isForm(node) {
	return node != null && node.nodeType == 1
		&& node.tagName.toLowerCase() == "form";
}

function getClassName(element) {
    var className = element.getAttribute("class");
    if (className == null) {
        className = element.getAttribute("className");
    }
    return className;
}

function setClassName(element, className) {
    element.setAttribute("class", className);
    element.setAttribute("className", className);
}

function isBlank(str) {
	return str==null || str.trim().length==0;
}

function isValidEmail(str) {
	return str!=null && str.search(/.+@.+\\.[a-z]+/) != -1;
}

function submitForgotPassword() {
	var url = "forgotpassword.do?fpemail="
		+ document.getElementById("eMailInputId").value;
	document.location = url;
}

function submitParentForm(id) {
	submitParentFormHelper(document.getElementById(id));
}

function submitParentFormHelper(child) {
	if (isForm(child)) {
		child.submit();
	} else if (child.parentNode != null) {
		submitParentFormHelper(child.parentNode);
	}
}

function expandBox(sectionId) {
	setClassName(document.getElementById(sectionId + "_collapsed"), "hiddenboxcontent");
	setClassName(document.getElementById(sectionId + "_expanded"), "visibleboxcontent");
}

function collapseBox(sectionId) {
	setClassName(document.getElementById(sectionId + "_collapsed"), "visibleboxcontent");
	setClassName(document.getElementById(sectionId + "_expanded"), "hiddenboxcontent");
}
/* 
 * TrialUser
 */
function toggleCheckBox(checkBoxId){
	$(checkBoxId)[0].value = $(checkBoxId)[0].value == 'true' ? 'false' : 'true';
}
/*
My bizbook 
 */
function checkboxToggled(demo) {
	var cbCount = countCheckedBoxes();
    if(demo=='true'){
        setYellowButtonEnabled("printItem", cbCount > 0);
        setYellowButtonEnabled("compareItem", true);
        setYellowButtonEnabled("deleteItem", false);
    }else {
        setYellowButtonEnabled("printItem", cbCount > 0);
        setYellowButtonEnabled("deleteItem", cbCount > 0);
        setYellowButtonEnabled("compareItem", cbCount > 1);
    }
}

function countCheckedBoxes() {
	var count = 0;
	var inputs = document.getElementsByTagName("input");

	for (var i=0; i<inputs.length; ++i) {
		if (inputs[i].getAttribute("type") == "checkbox" && inputs[i].getAttribute("name") == "strids" && inputs[i].checked) {
			++count;
		}
	}

	return count;
}

function setYellowButtonEnabled(parentId, enabled) {
	var parent = document.getElementById(parentId);
	if (parent != null) {
		setYellowButtonEnabledHelper(parent, enabled);
	}
}

function setYellowButtonEnabledHelper(parent, enabled) {
	var fromColour = enabled ? "grey" : "yellow";
	var toColour = enabled ? "yellow" : "grey";
    var child;

    for (child=parent.firstChild; child!=null; child=child.nextSibling) {
    	if (child.nodeType == 1) {
	    	var className = getClassName(child);
			if (className != null && className.indexOf(fromColour) == 0) {
				setClassName(child, className.replace(fromColour, toColour));
			}
			if (isSubmit(child)) {
				child.disabled = !enabled;
			}
			setYellowButtonEnabledHelper(child, enabled);
		}
	}
}

/* logic for Search */

var WHO_FIELD_ID = "who";
var WHAT_FIELD_ID = "what";
var WHERE_FIELD_ID = "where";
var FIRST_NAME_FIELD_ID = "firstName";
var LAST_NAME_FIELD_ID = "lastName";
var COMPANY_FIELD_ID = "company";
var ADDRESS_FIELD_ID = "address";
var ZIP_CODE_FIELD_ID = "zipCode";
var CITY_FIELD_ID = "city";
var MSISDN_FIELD_ID = "msisdn";
var ORG_NUMBER_FIELD_ID = "orgNumber";
var INPUT_FIELD_IDS = new Array(WHO_FIELD_ID, WHAT_FIELD_ID, WHERE_FIELD_ID,
	FIRST_NAME_FIELD_ID, LAST_NAME_FIELD_ID, COMPANY_FIELD_ID, ADDRESS_FIELD_ID,
	ZIP_CODE_FIELD_ID, CITY_FIELD_ID, MSISDN_FIELD_ID, ORG_NUMBER_FIELD_ID);

function onfocusinputwho(){
    onfocusinput(WHO_FIELD_ID);
}
function onfocusinputwhat(){
    onfocusinput(WHAT_FIELD_ID);
}
function onfocusinputwhere(){
    onfocusinput(WHERE_FIELD_ID);
}
function onfocusinputfirstname(){
    onfocusinput(FIRST_NAME_FIELD_ID);
}
function onfocusinputlastname(){
    onfocusinput(LAST_NAME_FIELD_ID);
}
function onfocusinputcompany(){
    onfocusinput(COMPANY_FIELD_ID);
}
function onfocusinputaddress(){
    onfocusinput(ADDRESS_FIELD_ID);
}
function onfocusinputzipcode(){
    onfocusinput(ZIP_CODE_FIELD_ID);
}
function onfocusinputcity(){
    onfocusinput(CITY_FIELD_ID);
}
function onfocusinputmsisdn(){
    onfocusinput(MSISDN_FIELD_ID);
}
function onfocusinputorgnumber(){
    onfocusinput(ORG_NUMBER_FIELD_ID);
}

function onfocusinput(inputFieldId){
	for (var i=0; i<INPUT_FIELD_IDS.length; ++i) {
    	var input = document.getElementById(INPUT_FIELD_IDS[i]);
    	if (inputFieldId == INPUT_FIELD_IDS[i]) {
			if (isInTooltipState(input)) {
				input.value = "";
				setTooltipState(input, false);
			}
		} else if (!isInTooltipState(input) && isBlank(input.value)) {
			setTooltipText(INPUT_FIELD_IDS[i]);
		}
	}
}

function onloadsimpleSearch(){
    for (var i=0; i<INPUT_FIELD_IDS.length; ++i) {
    	var input = document.getElementById(INPUT_FIELD_IDS[i]);
    	if (isBlank(input.value)) {
			setTooltipText(INPUT_FIELD_IDS[i]);
		}else {
            setTooltipState(input,false);
        }
    }
}

function setTooltipText(inputId) {
	var element = document.getElementById(inputId);
	setTooltipState(element, true);
	if (inputId == WHO_FIELD_ID) {
		element.value = "F\u00f6rnamn, Efternamn";
	} else if (inputId == WHAT_FIELD_ID) {
		element.value = "F\u00f6retag, Orgnr, Telnr";
	} else if (inputId == WHERE_FIELD_ID) {
		element.value = "Adress, Ort, Postnr";
	} else if (inputId == FIRST_NAME_FIELD_ID) {
		element.value = "F\u00f6rnamn";
	} else if (inputId == LAST_NAME_FIELD_ID) {
		element.value = "Efternamn";
	} else if (inputId == COMPANY_FIELD_ID) {
		element.value = "F\u00f6retagsnamn";
	} else if (inputId == ADDRESS_FIELD_ID) {
		element.value = "Adress";
	} else if (inputId == ZIP_CODE_FIELD_ID) {
		element.value = "Postnr";
	} else if (inputId == CITY_FIELD_ID) {
		element.value = "Ort";
	} else if (inputId == MSISDN_FIELD_ID) {
		element.value = "Tel (ex: 031-123456)";
	} else if (inputId == ORG_NUMBER_FIELD_ID) {
		element.value = "Organisationsnummer";
	}
}

function isInTooltipState(input) {
	return getClassName(input) == "inputtooltip" ;
}

function setTooltipState(input, tooltip) {
	setClassName(input, tooltip ? "inputtooltip" : "input");
}

function clearTooltipTexts() {
	for (var i=0; i<INPUT_FIELD_IDS.length; ++i) {
    	var input = document.getElementById(INPUT_FIELD_IDS[i]);
    	if (isInTooltipState(input)) {
			input.value = "";
		}
    }
}

function switchToAdvancedSearch() {
     $('#simpleSearchFormId').hide();
     $('#advancedSearchFormId').show();
}

function switchToSimpleSearch() {
      $('#simpleSearchFormId').show();
        $('#advancedSearchFormId').hide();
}

function beforeSimpleSearch() {
	clearTooltipTexts();
	document.getElementById(FIRST_NAME_FIELD_ID).value = "";
	document.getElementById(LAST_NAME_FIELD_ID).value = "";
	document.getElementById(COMPANY_FIELD_ID).value = "";
	document.getElementById(ADDRESS_FIELD_ID).value = "";
	document.getElementById(ZIP_CODE_FIELD_ID).value = "";
	document.getElementById(CITY_FIELD_ID).value = "";
	document.getElementById(MSISDN_FIELD_ID).value = "";
	document.getElementById(ORG_NUMBER_FIELD_ID).value = "";
}

function beforeAdvancedSearch() {
	clearTooltipTexts();
	document.getElementById(WHO_FIELD_ID).value = "";
	document.getElementById(WHAT_FIELD_ID).value = "";
	document.getElementById(WHERE_FIELD_ID).value = "";
}

function resetSearchfields() {
      for (var i=0; i<INPUT_FIELD_IDS.length; ++i) {
			setTooltipText(INPUT_FIELD_IDS[i]);
            setTooltipState(document.getElementById(INPUT_FIELD_IDS[i]),true);
        }
}

/*
 * Logic for show company page.
 */
var SCA_LOADED = 4;
var SCA_REQUEST;

function showContact(id, demo) {
    var i;
    var className;

    var listItems = document.getElementsByTagName("li");
    for (i=0; i<listItems.length; ++i) {
        className = getClassName(listItems[i]);
        if (className != null && (className == "evenselected")) {
            setClassName(listItems[i], "even");
        }else if(className != null &&(className == "oddselected")) {
            setClassName(listItems[i], "odd");
        }
    }

    var listItem = document.getElementById("clistdiv_" + id);
    setClassName(listItem, getClassName(listItem) + "selected");

    listItem = document.getElementById("clistspan_" + id);
    if (listItem != null) {
        setClassName(listItem, getClassName(listItem) + "selected");
    }


    var url = "showcontact.do?contactId=" + id;
    if (demo) url += "&demo=true";

    setShowCompanyAjaxContent("<div class=\"normalinfotext\" style=\"padding-top: 40px; text-align: center\">"
            + "<i>Laddar kontakt...</i><br/>"
            + "<img style=\"margin-top: 10px\" src=\"images/rolling_progress.gif\"/>"
            + "</div>");

    $.get(url, function(data){
        setShowCompanyAjaxContent(data);
        //reinitialiseEvents();
        setAddContactHandler();
    });

}

function setShowCompanyAjaxContent(content) {
    document.getElementById("ajaxcontent").innerHTML = content;
}

function openPromoteStandardDialog() {
    tb_show('','#TB_inline?height=300&amp;width=360&amp;inlineId=promoteStandardDialogId',false);
}

function loadVerksamhet(worksiteId, companyNumber,demo){
    var url ="showverksamhet.do?companyNumber="+companyNumber+"&worksiteId="+worksiteId;
    if (demo) url += "&demo=true";
    $.get(url, function(data){
        document.getElementById("verksamhet_expanded").innerHTML = data;
    });
}

function loadkoncerninfo(companyNumber, demo){
     var url ="showkoncerninfo.do?companyNumber="+companyNumber;
     if (demo) url += "&demo=true";

    $.get(url, function(data){
        document.getElementById("Koncerninformation_expanded").innerHTML = data;
    });
}

  /**
   * logic for signup flow
   */
    function hideCardForm() {
        var card = document.getElementById('card');
        var invoice = document.getElementById('faktura');
        var cardText = document.getElementById('dialogcardtext');
        var invoiceText = document.getElementById('dialoginvoicetext');
        setClassName(invoiceText,"show");
        setClassName(cardText,"hide");
        setClassName(card, "hiddenform");
        setClassName(invoice, "showform");
    }

    function hideInvoiceForm() {
        var card = document.getElementById('card');
        var invoice = document.getElementById('faktura');
        var cardText = document.getElementById('dialogcardtext');
        var invoiceText = document.getElementById('dialoginvoicetext');
        setClassName(card, "showform");
        setClassName(invoice, "hiddenform");
        setClassName(cardText,"show");
        setClassName(invoiceText,"hide");
    }

    function enableInvoiceFields() {
        disableFields(false);
    }
    function disableInvoiceFields() {
        disableFields(true);
        var invoicechildren = $('#invoice').children();
    	invoicechildren[0].innerHTML = $('#address')[0].value;
    	invoicechildren[1].innerHTML = $('#zipcode')[0].value;
    	invoicechildren[2].innerHTML = $('#city')[0].value;
    	$('#invoiceAddress')[0].value = $('#address')[0].value;
    	$('#invoiceZipcode')[0].value = $('#zipcode')[0].value;
    	$('#invoiceCity')[0].value = $('#city')[0].value;
    }
    function disableFields(showOrNot) {
        $('#invoiceAddress')[0].disabled = showOrNot;
        $('#invoiceZipcode')[0].disabled = showOrNot;
        $('#invoiceCity')[0].disabled = showOrNot;
    }
    function changeInvoiceAddress(){
    	var invoicechildren = $('#invoice').children();
    	invoicechildren[0].innerHTML = $('#invoiceAddress')[0].value;
    	invoicechildren[1].innerHTML = $('#invoiceZipcode')[0].value;
    	invoicechildren[2].innerHTML = $('#invoiceCity')[0].value;
    }
    
    function submitPaymentForm(){
    	enableInvoiceFields();
    	$('#hiddenSubmit')[0].click();
    }
