﻿/*function ApplyTemplate(msg)
{
$('#searchWords').append(msg.d);
}

function showInfo(row) 
{
$("#" + row).toggle();
return false;
}

function DisplayError( msg )
{
$('#searchWords').append(msg.responseText);
}*/

$(document).ready(function () {
    $(".img-langSwitcher").click(function () {
        SwitchLanguage($(this).attr("id"));
    });

    $('.nyroModal').nyroModal();

    $(".pageswitch").click(function () {
        ShowPage($(this).attr('id'));
    });

    $(".mtalSwitch").click(function () {
        ShowSubPage($(this).attr('id'));
    });

    $(".manntal-more").click(function () {
        ShowManntalDetail($(this).attr('id'));
    });


    $('.fontresizer').click(function () {

    
      //  fontResize(this.id, $(this).attr('container'));
       // alert($(this).attr('container'));
        //        var ourText = $($(this).attr('container')); //$('p, table, label'); //, div#sub-links
        //        var currFontSize = ourText.css('fontSize');

        //        var finalNum = parseFloat(currFontSize, 10);
        //        var stringEnding = currFontSize.slice(-2);
        //        if (this.id == 'large') {
        //            finalNum *= 1.1;
        //            $.cookie('manntal.fontsize.current', finalNum + stringEnding, { path: '/', expires: 10 });
        //        }
        //        else if (this.id == 'small') {
        //            finalNum /= 1.1;
        //            $.cookie('manntal.fontsize.current', finalNum + stringEnding, { path: '/', expires: 10 });
        //        }
        //        else if (this.id == 'reset') {
        //            $.cookie('manntal.fontsize.current', null);
        //            window.location.reload();
        //        }

        //        if (parseInt(finalNum) < 20 && parseInt(finalNum) > 10) {
        //            ourText.css('fontSize', finalNum + stringEnding);
        //        }
    });

    if ($.cookie('manntal.fontsize.current') != null) {
        var cookieFont = $.cookie('manntal.fontsize.current');
        $('.tabs-container').css('fontSize', cookieFont);
    }
});

function fontResize(size, container) {

    var ourText = $(container); 
    var currFontSize = ourText.css('fontSize');
    var finalNum = parseFloat(currFontSize, 10);
    var stringEnding = currFontSize.slice(-2);
    if (size == 'large') {
        finalNum *= 1.1;
        $.cookie('manntal.fontsize.current', finalNum + stringEnding, { path: '/', expires: 10 });
    }
    else if (size == 'small') {
        finalNum /= 1.1;
        $.cookie('manntal.fontsize.current', finalNum + stringEnding, { path: '/', expires: 10 });
    }

    if (parseInt(finalNum) < 20 && parseInt(finalNum) > 10) {
        ourText.css('fontSize', finalNum + stringEnding);
    }
}

function ReCenterContentContainer() {
    if ($(".tabs-nav").outerWidth() > $("#container").outerWidth()) {
        $("#content-wrapper").css("margin-left", -(($(".tabs-nav").outerWidth() - $("#container").outerWidth()) / 2));
    }
}

function ShowPage(pageId) {
    $('.subpage-container').each(function() {
        if ($(this).attr('id') == pageId + '-content') {
            if ($(':visible', this).length == 0) {
                $("#" + $(this).attr('id').replace('-content', '')).attr('class', 'pageswitch current');
                $(this).fadeIn();
            }
        }
        else {
            $("#" + $(this).attr('id').replace('-content', '')).attr('class', 'pageswitch');
            $(this).hide();
        }
    });

    setFooter();
}

function ShowSubPage(pageId) {
    $('.manntalinfo-wrapper').each(function() {
        if ($(this).attr('id') == pageId + '-content') {
            if ($(':visible', this).length == 0) {
                $("#" + $(this).attr('id').replace('-content', '')).attr('class', 'mtalSwitch current');
                $(this).fadeIn();
            }
        }
        else {
            if ($(this).attr('class') != 'umManntol-container') {
                $("#" + $(this).attr('id').replace('-content', '')).attr('class', 'mtalSwitch');
                $(this).hide();
            }
        }
    });

    setFooter();
}

function ShowManntalDetail(contId) {

    $("#" + contId + '-detail').toggle();

    setFooter();
}


function SwitchLanguage(lang) {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/Session.asmx/SwitchLanguage",
        data: "{'code':'" + lang + "'}",
        dataType: "json",
        async: false,
        success: function(msg) {

            //alert(location.href.replace(/\#/, ''));
            var rand = Math.random();
            var loc = location.href;

            if (loc.indexOf('?') != -1) {
                loc = loc + '&' + rand;
               // alert(loc);
            }
            else {
                loc = loc + '?' + rand;
               // alert(loc);
            }
            location.replace(loc);
            //location.replace(location.href.replace(/\?.*$/, '') + '?' + Math.random()); //reload page after language switch
        }
    });
}



//TODO: þetta fall þarf að vera generic
function SendToFriend() {
    
 
    var language = $("#sendReciver").val();

    var sendandi = $("#sendToFriend-sendandi").val();
   
    var mottakandi = $("#sendToFriend-mottakandi").val();
    var efni = $("#sendToFriend-taContent").html(); //þarf að breyta þessu í töflu
    var skilabod = $("#sendToFriend_taMessage").val();
    var theData = "{'sendandi':'" + sendandi + "', 'mottakandi':'" + mottakandi + "', 'skilabod':'" + skilabod + "', 'efni':'" + efni +"', 'language':'"+language+ "'}";
  
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "services/Email.asmx/SendToFriend",
        data: theData,
        dataType: "json",
        async: false,
        success: function(msg) {
            //TODO: success message
            ShowMiniMessagebar('success', labelSend);
        },
        error: function(XMLHttpRequest, text, error) {
            ShowMiniMessagebar('error', 'Villa kom upp við að senda póst!');
        }
    });
}

function SendAbending() {

    var sendandi = $("#sendToFriend-sendandi").val();
    var efni = $("#sendToFriend-taContent").html();
    var skilabod = $("#sendToFriend_taMessage").val();

    var theData = "{'sendandi':'" + sendandi + "', 'skilabod':'" + skilabod + "'}";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/services/Email.asmx/SendAbending",
        data: theData,
        dataType: "json",
        async: false,
        success: function(msg) {
            //TODO: success message
            ShowMiniMessagebar('success', labelSend);
        },
        error: function(XMLHttpRequest, text, error) {
            ShowMiniMessagebar('error', 'Villa kom upp við að senda póst!');
        }
    });
}


function ShowMiniMessagebar(state, msg) {
    $('#sendform-message-container').attr('class', state);
    $('#sendform-message-container').html(msg);
    $('#sendform-message-container').fadeIn();
}

function HideMiniMessagebar() {
    $('#sendform-message-container').fadeOut();
}

// this function is called when the user accesses the page from facebook or other external site
function DirectPerson(_keyValues) {


    var arr = eval(_keyValues);

    $("#inpSearchType").val("advanced");
    $("#searchTextBox").val(arr[2]);
    $("#tbHeimili").val(arr[3]);
    $("#tbStada").val(arr[4]);
    $("#tbSysla").val(arr[5]);
    $("#tbSokn").val(arr[6]);
    //TODO - vantar kyn og aldur hér inn
    SetSingleManntalCheckbox(arr[0]);

    senda_button_onClick(1);

    showInfo(arr[1]);

    activateSearchTab(arr[0]);

    ResetSearchForm(true);
    
}

function activateSearchTab(mtal) {
    $('.tabs-container').each(function() {
        if ($(this).attr('id') == 'resulttab-' + mtal) {
            $(this).attr('class', 'tabs-container');
        }
        else {
            $(this).attr('class', 'tabs-container tabs-hide');
        }
    });

    $('#li-' + mtal).attr('class', 'tabs-selected');
}

function OpenFormPrint(contentContainer) {

    var cont = '<div id="sendform-container"><fieldset><legend>' + langInfoFromCensus + '</legend>';
    cont += '<div id="sendToFriend-taContent" class="printSend-content">';
    cont += $("#" + contentContainer + "").html();
    cont += '</div>';
    cont += '</fieldset>';
    cont += '<div id="btn-container" style="margin-right:4px" class="button">'+printBaer + '</div></div>';
    //cont += "<a id='print-button' href='' class='button'>prenta</a>";c
    $.nyroModalManual({
        minHeight: 360,
        minWidth: 640,
        content: cont
    });

    $("div#btn-container").click(function() {
    if(contentContainer == 'content-baer-container') //hugsanlega ekki málið er aðeins stutt fyrir IE 8 og FF 3.5.3
    {   
      $("div#sendToFriend-taContent").printArea(); //ekki hægt að nota fieldset ef meira en 1 síða
    }
    else{
  
          $("div#sendform-container").printArea(); 
          }
        return false;
    });
}

function OpenFormSendFriend(contentContainer, strDirectUrl) {

    var retVal;
    var cont = $("#" + contentContainer + "").html();

    cont += '<a href="' + strDirectUrl + '">skoða nánar á manntalsvef</a>'; //vantar að troð inn þýðingu

 
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/QueryWorker.asmx/ShowFormSendToFriend",
        data: "{'content':'" + cont + "'}",
        dataType: "json",
        async: false,
        success: function(msg) {
            retVal = msg.d;
        }
    });

    $.nyroModalManual({
        minHeight: 360,
        minWidth: 640,
        content: retVal
    });

    $("#frmSendfriend").validationEngine({
        inlineValidation: true,
        success: function() { SendToFriend(); return false; },
        failure: false
    });
}

jQuery.fn.stripTags = function() {
return this.replaceWith(this.html().replace(/<a\b[^<>]*?\b(href=\s*=\s*(?:"[^"]*"|'[^']'|\S+))/
, ''));
};

function OpenFormSendFriend(contentContainer, strDirectUrl, removemorelinks) {

    var retVal;
    var cont = $("#" + contentContainer + "").html();
   if (removemorelinks) {
       cont = cont.replace(/\s*href\s*=\s*('[^']*'|"[^"]*")/ig, '');
       cont = cont.replace(/\s*onclick\s*=\s*('[^']*'|"[^"]*")/ig, '');
   }

   cont += '<hr /><a href="' + strDirectUrl +'">skoða nánar á manntalsvef</a>';


    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "QueryWorker.asmx/ShowFormSendToFriend",
        data: "{'content':'" + cont + "'}",
        dataType: "json",
        async: false,
        error: function() {
        },
        success: function(msg) {
            retVal = msg.d;
        }
    });

    $.nyroModalManual({
        minHeight: 360,
        minWidth: 740,
        content: retVal
    });

    $("#frmSendfriend").validationEngine({
        inlineValidation: true,
        success: function() { SendToFriend(); return false; },
        failure: false
    });
}

function HideAllValidationMessages() {
    $.validationEngine.closePrompt('.formError', true);
}

function OpenFormSendFacebook(_shareUrl) {

    $.nyroModalManual({
        minHeight: 436,
        minWidth: 650,
        url: _shareUrl
    });
}

function OpenFormLogin() {
    $.nyroModalManual({
        minHeight: 200,
        minWidth: 200,
        url: "/Login.aspx"
    });
}



/* footer */
function getWindowHeight() {
    var windowHeight = 0;
    if (typeof (window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
    }
    else {
        if (document.documentElement && document.documentElement.clientHeight) {
            windowHeight = document.documentElement.clientHeight;
        }
        else {
            if (document.body && document.body.clientHeight) {
                windowHeight = document.body.clientHeight;
            }
        }
    }
    return windowHeight;
}
function setFooter() {
    if (document.getElementById) {
        var windowHeight = getWindowHeight();
        if (windowHeight > 0) {
            var contentHeight = document.getElementById('page-wrapper').offsetHeight;
            var footerElement = document.getElementById('page-footer');
            var footerHeight = footerElement.offsetHeight;
            if (windowHeight - (contentHeight + footerHeight) >= 0) {
                footerElement.style.position = 'relative';
                footerElement.style.top = (windowHeight - (contentHeight + footerHeight)) -20 + 'px';
            }
            else {
                footerElement.style.position = 'static';
            }
        }
    }
}

function createUUID() {
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    var uuid = s.join("");
    return uuid;
}

function resizeNyroModal() {
    $.nyroModalSettings({
//        width: $(".baer-share-container").width() + 20,
//        height: $(".baer-share-container").height() + 50
    });
}


function toExcel(sContainer) {
    alert('not implemented');
}

window.onload = function() {
    setFooter();
}
window.onresize = function() {
    setFooter();
}

function getUrl() {
//pakka hér saman öllu controlerum
// í base64. nota eigin base 64 þar sem hinn
//server basein var of advance...uc?
//1.manntalsselctorinum

  var allVals = [];
    $('.multiSelectOptions :checked').each(function() {
        if ($(this).val() != 'on') {
            allVals.push($(this).val());
       
        }
    });
 //2. leitarorðið (nafn)
 var nafn = $("#searchTextBox").attr("value");
 var heimili = $("#tbHeimili").attr("value");
 var stada = $("#tbStada").attr("value");
 var sysla = $("#tbSysla").attr("value");
 var sokn = $("#tbSokn").attr("value");
 var aldur = $("#tbAldur").attr("value");
 var searchType = $("#inpSearchType").attr("value");
 
 var kyn = "ótilgreint";
 if (($('#kynKarl').attr('checked')) && ($('#kynKona').attr('checked'))) {
                kyn = "";
    }
else {
if ($('#kynKarl').attr('checked')) {
               kyn = "karl";
    }
if ($('#kynKona').attr('checked')) {
                    kyn = "kona";
    }
 }
 var numResult =   $("#numResults").attr("value");
 
var url =  allVals + '+' + nafn + ';' + heimili + ';' + stada + ';' + sysla + ';' + sokn + ';' + kyn + ';' + aldur + ';' + searchType + ';' + numResult;

url = '?bla=' + Base64.encode(url); 
return url;
}
 var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
    
		return string;
	}
 
}
function DirectFromUrl(stillingar) {


    var url = document.location;
    var strippedUrl = url.toString().split("?bla=");

  if(strippedUrl.length != 1 || stillingar != '')
  {
    

    if(strippedUrl.length >= 2)
    {
          
            stillingar = Base64.decode(strippedUrl[1]);
    }
    
    var end = stillingar.toString().indexOf('+');
    var manntol = stillingar.toString().substring(0,end);
 
    var rest = stillingar.toLocaleString().substring(end + 1,stillingar.toLocaleString().length);

    var box = new Array();
    
    box = rest.split(';');
       
   // var nafn = stillingar.toString().split(
     
    var arrmanntol = new Array();
    
    arrmanntol = manntol.split(',');

    $("#numResults").val(box[8]);
   
    $("#searchTextBox").val(box[0]);
    $("#searchTextBox").focus();
    $("#searchTextBox").blur();
    $("#tbHeimili").val(box[1]);
    $("#tbHeimili").blur();
    $("#tbStada").val(box[2]);
    $("#tbStada").blur();
    $("#tbSysla").val(box[3]);
    $("#tbSysla").blur();
    $("#tbSokn").val(box[4]);
    $("#tbSokn").blur();
     
     if(box[5] == 'kona')
     {
       $("#kynKarl").attr('checked', false);
       $("#kynKona").attr('checked', true);
     }
     if(box[5] == 'karl')
     {
       $("#kynKarl").attr('checked', true);
       $("#kynKona").attr('checked', false);
     }
     if(box[5] == '')
     {
        $("#kynKarl").attr('checked', true);
        $("#kynKona").attr('checked', true);
     }
     if(box[5] == 'ótilgreint')
     {
        $("#kynKarl").attr('checked', false);
        $("#kynKona").attr('checked', false);
     }
     $("#tbAldur").val(box[6]);
     $("#tbAldur").blur();
     $("#inpSearchType").val(box[7]);
   
     if(box[7].toString() == 'simple')
     {
         SetSearchSimple();
     }
     if(box[7].toString() == 'advanced')
     {
        SetSearchAdvanced();
     }
     
         
    //setja manntol í array og svo each inn í þetta
    var iMan = arrmanntol.length;
    for(var x = 0; x <= iMan; x++)//for er skemmtilegara en each
    { 
        //vantar að setja í boxið gildinn
         SetManntalCheckbox(arrmanntol[x]);
     
         $(".multiSelect").attr("value", arrmanntol);
        
    }

    senda_button_onClick(1);

    showInfo('baer-id_1703_29754');
   
    activateSearchTab(arrmanntol[0]);
   }
  //  ResetSearchForm(true);
}
