// custom functions


/**
*  Some vital global variables for the timer
*/
var timerId = 0;
var counterId = 0;
var COOKIE_NAME;
var COOKIE_OPTIONS;

/**
* Show modalpopup
*/
function showSurvey(cookie) {

    COOKIE_NAME = cookie;
    COOKIE_OPTIONS = { path: '/', expires: 20 };

    if ($.cookie(COOKIE_NAME) != "no" && $.cookie(COOKIE_NAME) != "yes") {

        startTimer();
        $("#modal").fadeIn("slow");
        $("#bannerwrapper").fadeIn("slow");

        $("html").click(function() {
            clickLater(COOKIE_NAME, COOKIE_OPTIONS);
            closeBanner(COOKIE_NAME, COOKIE_OPTIONS);
        });

    }
    else {
        $("#modal").remove();
        return false;
    }

}



/**
*  Start the timer
*/
function startTimer() {
    var time = 120000;
    alertTimerId = setTimeout('closeBanner()', time);
    updateCounter(time/1000);
}
/**
*  Reset the Timer
*/
function resetTimer() {
    clearTimeout(alertTimerId);
    clearTimeout(counterId);
    startTimer();
}
/**
*  Refresh the Page
*/
function closeBanner() {
    $("#modal").fadeOut("slow");
    $("#bannerwrapper").fadeOut("slow");
}
/**
*  Update the on-page Counter
*/
function updateCounter(count) {
    count = count - 1;
    $('#timer').html(count);
    counterId = setTimeout('updateCounter(\'' + count + '\')', 1000);
}

/** 
*  User clicked 'no' - Save that in cookie
*/
function clickNo() {

    $.cookie(COOKIE_NAME, 'no', COOKIE_OPTIONS);
    closeBanner();

}
/** 
*  User clicked 'no' - Save that in cookie
*/
function clickYes(url) {
    

    $.cookie(COOKIE_NAME, 'yes', COOKIE_OPTIONS);
    window.open(url, 'survey');
    closeBanner();
}
/** 
*  User clicked 'later' - save that in cookie
*/
function clickLater() {

    $.cookie(COOKIE_NAME, 'later', COOKIE_OPTIONS);
    closeBanner();

}
function selectComments() {

    $('div.container_article_footer div.header, div.container_article_footer div.header_selected').each(function(i, obj) {

        if ($(obj).hasClass("header_selected")) {
            $(obj).attr('class', 'header');
        }
        if ($(obj).hasClass("comments")) {
            $(obj).attr('class', 'header_selected');
        }

    });


}
function AddToErrorMessageArray(arr, newText) {
    arr[arr.length] = newText;
}
function postComment(ref) {

   var data = '';


   var itemRef = $(ref).parent().parent().parent().parent().parent();

   data = data + '&pageid=' + $(itemRef).find('input.refField').val();

    $(itemRef).find("input:visible,select:visible,textarea").each(function(i, _obj) {

        if (this.type === 'submit') {
            
        }
        else if (this.type === 'checkbox') {

        if ($(itemRef).find('#CheckBoxAgree').attr('checked')) {
                data = data + '&' + this.id + '=' + 'true';
            }
            else {
                data = data + '&' + this.id + '=' + 'false';
            }
        }
        else {
            data = data + '&' + this.id + '=' + escape(this.value);
        }
        
    });


    //validate
    if (validateComment(itemRef)) {

        //post data
        var _url = "/Handlers/comment.ashx?f=savecomment" + data;
        //console.log(_url);
        $.ajax({
            type: "post",
            url: encodeURI(_url),
            success: function(msg) {
                //Handle success event
                $(itemRef).find("p.result").html(unescape("Din kommentar %E4r inlagd."));
                window.location.href = window.location.href;
            },
            error: function(xhr, ajaxOptions, thrownError) {
            //Log error
               $(itemRef).find("p.result").html(unescape("Ett%20fel%20uppstod.%20Var%20god%20f%F6rs%F6k%20igen"));
                
            }
        });

        $(itemRef).find("p.result").css("display", "block");
        

    }
    else {
        $(itemRef).find("p.result").css("display", "block");
    }

}



function validateComment(itemRef) {
    var errorMessages = new Array();

    var isValid = true;

    if ($(itemRef).find('#TextBoxComment').val().length < 1) {
        isValid = false; 
        AddToErrorMessageArray(errorMessages, unescape("Du m%E5ste skriva in en kommentar."));
    }
    if ($(itemRef).find('#TextBoxComment').val().length > 1000) {
        isValid = false;
        AddToErrorMessageArray(errorMessages, unescape("Kommentaren f%E5r max inneh%E5lla 1000 tecken."));
    }
    if ($(itemRef).find('#TextBoxName').val().length < 1) {
        isValid = false;
        AddToErrorMessageArray(errorMessages, unescape("Du m%E5ste ange ditt namn."));
    }

    if ($(itemRef).find('#TextBoxSender').val().length < 1) {
        isValid = false;
        AddToErrorMessageArray(errorMessages, unescape("Du m%E5ste ange din e-postadress."));

    } 
    else {

        var email = $(itemRef).find('#TextBoxSender').val();
          var reg = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
            if (!reg.test(email)) {
                isValid = false;
                AddToErrorMessageArray(errorMessages, unescape("Din e-postadress %E4r ej giltig."));
            }
        
        }


        if ($(itemRef).find('#CheckBoxAgree').length > 0) {
            if ($(itemRef).find('#CheckBoxAgree').attr('checked') !== true) {
                isValid = false;
                AddToErrorMessageArray(errorMessages, unescape("Du m%E5ste godk%E4nna villkoren f%F6r att skicka kommentaren."));
            }
        }

    if (!isValid) {
        var completeMsg = "<div class='error'>";
        completeMsg += unescape("Ett fel uppstod n%E4r kommentaren skulle l%E4ggas in!");
         completeMsg += "<ul>";
        for (id = 0; id < errorMessages.length; id++) {
            completeMsg += "<li>" + errorMessages[id] + "</li>";
        }

        completeMsg += "</ul>";
        completeMsg += "</div>";
        

        errorMessages = completeMsg;
        $(itemRef).find("p.result").html(errorMessages);
        
    }
    
    return isValid;
        
}
