function checkEmpty(value) {
    return value.length > 0;
}

function checkPhoneNbr(value) {
    var numbers = value.replace(/\s+|\-+/g, '');
    return /^ *[0-9]+ *$/.test(numbers);
}

function checkEmail(value) {
    return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value);
}


function fetchCompanyByNameAndCountry(companyName, country) {

    var responseData;
    $.ajax({
                type: "GET",
                dataType: "json",
                async: false,
                url: "/templates/soliditet/searchCompany.jsp?country=" + country + "&maxHits=20&q=" + companyName,
                success: function(response) {
                    responseData = response;
                },
                error: function(jqXHR, textStatus, errorThrown){
                }
            });
    return responseData;
}

function refineSearch() {

    var name = $('#refine-company-name').val();
    var address = $('#refine-company-address').val();
    var town = $('#refine-company-town').val();
    var phone = $('#refine-company-phone').val();

    var query = name + " " + address + " " + town + " " + phone;

    query =  name;

    jsonData = fetchCompanyByNameAndCountry(query,  $('.company-selector #searchCountry').val());
       $('table.hitlist tbody.hits tr.company-hit-row').remove();
    if(jsonData == null || jsonData.SearchResponse.hitCount == '0') {
        $('#no-hits-row').show();
    }
    else {
        var htmlString = createCompanyTable(jsonData);
        $('table.hitlist tbody.hits').prepend(htmlString);
    }

}

function socialSecurityNumberSECheck(nr) {
    if (!nr.match(/^(\d{2})(\d{2})(\d{2})\-(\d{4})$/)) {
        return false;
    }
    var now = new Date();
    var nowFullYear = now.getFullYear() + "";
    var nowCentury = nowFullYear.substring(0, 2);
    var nowShortYear = nowFullYear.substring(2, 4);

    var year = nr.substr(0, 2);
    var month = nr.substr(2, 2);
    var day = nr.substr(4, 2);
    var controlDigits = nr.substr(7, 4);

    var fullYear = (year * 1 <= nowShortYear * 1) ? (nowCentury + year) * 1 : ((nowCentury * 1 - 1) + year) * 1;
    var months = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

    if (fullYear % 400 == 0 || fullYear % 4 == 0 && fullYear % 100 != 0) {
        months[1] = 29;
    }

    if (month * 1 < 1 || month * 1 > 12 || day * 1 < 1 || day * 1 > months[month * 1 - 1]) {
        return false;
    }

    var allDigits = year + month + day + controlDigits;
    var nn = "";

    for (var n = 0; n < allDigits.length; n++) {
        nn += ((((n + 1) % 2) + 1) * allDigits.substring(n, n + 1));
    }

    var checksum = 0;

    for (var y = 0; y < nn.length; y++) {
        checksum += nn.substring(y, y + 1) * 1;
    }

    return (checksum % 10 == 0) ? true : false;
}

function contactMeForm(country, boxId, messageBoxId) {

    var box = $('.' +boxId);

    var description = "";
    description +=  $('.contactMe-hiddenheader', box).val();

    var form = $('.phoneContactForm',box);
    var fieldVal = $('.phone-feedback-field', box).val();

    if(checkEmpty(fieldVal) && checkPhoneNbr(fieldVal)) {
        description +=  ": " + fieldVal;
        description +=  "\r\n" + $('.contactMe-subject', box).val();
        if(country == 'SE') {
            webToLead('01220000000096i',$('.contact-me-header', box).text(),
                    $('.contactMe-hiddenheader', box).val(),description,"","","","",messageBoxId);
        } else {
            var email = $('.box-emailTo', box).val();
            sendFormAsEmail(email, email, $('.contact-me-header', box).text(), "", description,messageBoxId);
        }
    }
    else {
        event.returnValue = false;
    }
}


function sendFormAsEmail(to, from, subject, header, mailContent, objectID) {

    // TODO -- remove this after test
  //  to= "info@freebase.se";
    if(!checkEmpty(from)) {
        from = to;
    }
    if(!checkEmpty(header)) {
        header = subject;
    }
     showFormData(subject, mailContent);
     $('#sendFormButton').unbind('click').click( function() {
        var data = "from=" + from + "&to=" + to+ "&subject=" + subject + "&header=" + header +"&content=" + mailContent;
        var url = "/templates/soliditet/mailer.jsp";
        $('.form-overview').dialog('close');
        doPost(url, data, objectID);
     });
}

function webToCase(recordType, subject, description, email, retUrl, objectID) {

    showFormData(subject, description);
      $('#sendFormButton').unbind('click').click( function() {
        $('.form-overview').dialog('close');
        var data = "recordType="+recordType+"&subject="+escapeHTML(subject)+"&description="+escapeHTML(description)+"&email="+email+"&retUrl="+escapeHTML(retUrl);
        var url = "/templates/soliditet/pages/form/webToCase.jsp";
        doPost(url, data, objectID);
    });
}

function webToLead(recordType, subject, interestedFor, description, email ,firstName, lastName,retUrl, objectID) {

    showFormData(subject, description);

      $('#sendFormButton').unbind('click').click( function() {
		$('.form-overview').dialog('close');
        var data = "recordType="+recordType+"&subject="+escapeHTML(subject)+"&Intresserad_av__c="+escapeHTML(interestedFor)+"&description="+escapeHTML(description)+"&email="+email+"&first_name="+escapeHTML(firstName)+"&last_name="+escapeHTML(lastName)+"&retUrl="+escapeHTML(retUrl);
        var url = "/templates/soliditet/pages/form/webToLead.jsp";
		
        doPost(url, data,objectID);
		return false;
    });
}

function escapeHTML(str){
	
	return str.replace(/&/gi, "%26");
}

function showFormData(subject, description) {
    var div = $('.form-overview');
    div.attr('title' ,subject);
    description = description.replace(/\r\n/g, '<br/>');
    $('.overview-description', div).html(description);
    div.dialog({
                modal: true,
                width: 550,
			    minWidth: 500
            });
}

function doPost(url, data, objectID) {

    var dialogBox  = $('#dialog-message');
    var hiddenBox  = $('#dialog-message-' + objectID);
    var message = "";
    var returnUrl = "#";
    $('.returnLink', dialogBox).bind('click', function() {
        window.location.href = $('.returnLink', dialogBox).attr('href');
        return false;
    });
	
	$.ajaxSetup({ scriptCharset: "utf-8" ,
        contentType: "application/x-www-form-urlencoded; charset=UTF-8" });

    $.ajax({
                type: "POST",
                async: false,
                url: url,
                data:data,
                 success: function(response) {
                    returnUrl =  $('.returnLink', hiddenBox).attr('href');
                    $('.returnLink', dialogBox).attr('href', returnUrl);
                    $('.returnLink', dialogBox).trigger('click');
                },

                error: function(jqXHR, textStatus, errorThrown){

                    message =   $('.errorMessage', hiddenBox).text();
                    $('.returnLink', dialogBox).attr("href", "#");
                    dialogBox.dialog({
                                modal: true,
                                buttons: {
                                    OK: function() {
										dialogBox.dialog( "close" );
                                        $('.returnLink', dialogBox).trigger('click');
                                    }
                                },
                                close: function() {
                                    $('.returnLink', dialogBox).trigger('click');
                                }
                            });
                    $('.confirmMessage', dialogBox).text(message).show();
                }
            });
}

$(document).ready(function () {
    checkSquareList();
});

function checkSquareList() {
    $('li').each(function () {
	 if($(this).css('list-style-type') == 'square') {
        if ($(this).children('p').size() == 0) {
            $(this).html("<p>"+ this.innerHTML + "</p>");
        }
	 }
    });
}
