﻿$(document).ready(function() {

    origWidth = $('a.dsbButton').width();
    var dsbButton = $('a.dsbButton');
    //var wrapper = '<div class="' +dsbButton.attr("class") + '"></div>")';
    //dsbButton.wrap(wrapper);
    dsbButton.wrap('<div class="dsbButton"></div>');
    //$('div.dsbButton').css("width", origWidth + 12 + "px");

    //Somehow CSS3 selectors aren't supported yet other than the newest firefox and webkit browsers
    $(".aboutItem  h3:first").addClass("firstchild");
    $('.infiniteCarousel').infiniteCarousel();

    //Tracking with Google Analytics
    $('#content.frontpage a.trackMe').click(function() {
        try {
            var elTitle = "no title";
            if ($(this).attr('title') != '') { elTitle = $(this).attr('title'); }
            pageTracker._trackEvent($(this).attr('rel'), elTitle);
        } catch (err) { }
    });

    //Remove empty a href
    $('.providerLogoBox .iconLink').each(function() {
        if ($(this).attr('href') == '') {
            $(this).removeAttr('href');
        }
    });

    //Add navigation to Dagen i Dag widget
    $('#content.frontpage #dageniDag .navigation ul li').click(function() {
        var id = $(this).attr('rel');
        $('#content.frontpage #dageniDag ul li').removeClass('active');
        $('li#' + id).addClass('active');
    });

    // Calculate remaining chars
    $('.calcChars_1000').keyup(function() {
        var maxChars = 1000;
        var charsLeft = maxChars - $(this).val().length;
        var $digits = $('#charsLeftDigits');
        if (charsLeft < 0) {
            $(this).val($(this).val().substr(0, maxChars));
        }
        if (charsLeft < 0) { charsLeft = 0; }
        $digits.text(charsLeft);
    });
    DSB.rating.setup($('.itemRating'));
    $('.bezzerwizzerWidget .radioGroup').click(function() {
        $('.bezzerwizzerWidget .error').removeClass('error');
        $('.bezzerwizzerWidget .message').hide();
    });

    $('.contact input').focus(function() {
        $(this).parent().removeClass('error');
        $(this).next('.message').hide();
    });
    ResetFormfield($('.contact .name'), "");
    ResetFormfield($('.contact .adress'), "");
    ResetFormfield($('.contact .zipcode'), "");
    ResetFormfield($('.contact .city'), "");
});
// Validate Bezzerwizzer answer
function bezValidateAnswer() {
    //e.stopPropagation();
    if (!$('.bezzerwizzerWidget .radioGroup input:radio').is(':checked')) {
        $('.bezzerwizzerWidget .radioGroup').addClass('error');
        $('.radioGroup .message').text(bezzerwizzerMsg[4]).show();
        return false;
    }
    else {
        return true;
    }
 }

 // Validate Bezzerwizzer contact info
 function bezValidateContact() {
     //e.stopPropagation();
     var valSum = null;
     var valid = ValReq('.bezzerwizzerWidget .contact .city', bezzerwizzerMsg[5], valSum, bezzerwizzerMsg[3]) +
                    ValReq('.bezzerwizzerWidget .contact .zipcode', bezzerwizzerMsg[5], valSum, bezzerwizzerMsg[2]) +
		            ValReq('.bezzerwizzerWidget .contact .adress', bezzerwizzerMsg[5], valSum, bezzerwizzerMsg[1]) +
		            ValReq('.bezzerwizzerWidget .contact .name', bezzerwizzerMsg[5], valSum, bezzerwizzerMsg[0]);
    		     

        if (valid == 4) {
            return true;
        }
        else{
        return false;
        }
 }


//Rating
var DSB = {};

DSB.rating = {
	setup: function($elm) {
		properties = {
			maxRating: 5,
			serviceUrl: '/templates/Public/Services/RatingService.asmx/GetRatingState',
			postData: {
				id: $elm.find('.currentId').val()
			}
		},
		$.ajax({
			type: "POST",
			data: properties.postData,
			url: properties.serviceUrl,
			success: function(result, userContext, methodName) {
				if (result == null) {
					//server error
					DSB.rating.error($elm);
				}
				else {
					result = eval('(' + $('string', result).text() + ')');

					var ratingHTML = '';
					for (var i = 1; i <= properties.maxRating; i++) {
						ratingHTML += '<input type="radio" name="' + properties.postData.id + '" value="' + i + '" class="ratingStar"';
						ratingHTML += (i == result.ratingaverage) ? ' checked="checked"' : '';
						ratingHTML += '/>';
					}
					$elm.find('.ratingCount').text(result.ratingcount);
					$elm.prepend(ratingHTML);

					DSB.rating.attach($elm, result.hasrated);
				}
			},
			error: function(XMLHttpRequest, errorHeading, errorText) {
				//error
				DSB.rating.error($elm);
			}
		});

	},
	attach: function($elm, hasRated) {
		$elm.find('.ratingStar').rating({
			required: 'false',
			readOnly: hasRated,
			callback: function(value, link) {
				properties = {
					serviceUrl: '/templates/Public/Services/RatingService.asmx/AddRating',
					postData: {
						rank: value,
						id: $elm.find('.currentId').val(),
						type: $elm.find('.currentType').val()
					}

				},
				$.ajax({
					type: "POST",
					data: properties.postData,
					url: properties.serviceUrl,
					success: function(result, userContext, methodName) {
						if (result == null) {
							//server error
							DSB.rating.error($elm);
						}
						else {
							result = eval('(' + $('string', result).text() + ')');
							switch (result.added) {
								case true: //User has rated
									DSB.rating.succes($elm);
									break;
								case false: //User has not rated yet
									DSB.rating.error($elm);
									break;
							}
						}
					},
					error: function(XMLHttpRequest, errorHeading, errorText) {
						// error
						DSB.rating.error($elm);
					}
				});

			}
		});
	},
	error: function($elm) {
		$elm.find('.ratingText').text('Rating ikke tilgængelig');
		$elm.find('.ratingStar').rating('disable');
	},
	disable: function($elm) {
		$elm.find('.ratingStar').rating('disable');
	},
	succes: function($elm) {
		$elm.find('.ratingStar').rating('disable');
		$elm.find('.ratingText').fadeOut('fast').fadeIn('fast').fadeOut('fast').fadeIn('fast');
		$elm.find('.ratingCount').text(parseInt($elm.find('.ratingCount').text()) + 1);
	}
}






// validation
function ValReqMultiLine(ctrlId, msg, valsum) {
    return ValReq(ctrlId, msg, valsum, 'm');
}

function ValReq(ctrlId, msg, valsum, flags) {
    if (flags) {
        return Val(ctrlId, /^.+$/, msg, valsum, flags)
    }
    else {
        return Val(ctrlId, /^.+$/, msg, valsum)
    }
}

function ValReqDigits(ctrlId, msg, valsum) {
    return Val(ctrlId, /^\d+$/, msg, valsum)
}


function Val(ctrlId, regex, msg, valsum, flags) {
    var val = jQuery.trim($(ctrlId).val());
    var isMatch = false;
    if (flags) {
        isMatch = val.match(regex, flags);
    }
    else {
        isMatch = val.match(regex);
    }

    if (!isMatch) {
        showErrorMsg(ctrlId);
    }
    else if (val == flags) {
        showErrorMsg(ctrlId, msg);
    }
    else {
        return true;
    }
}

function showErrorMsg(ctrlId, msg) {
    $(ctrlId).parent().addClass('error');
    $('<div class="message" style="display: block">' + msg + '</div>"').insertAfter(ctrlId);
    
    return false;
 }
/* Reset form fields on focus*/
function ResetFormfield(elm, defaultValue) {
    $(elm).focus(function() {
        if (defaultValue != "") {
            if (this.value == defaultValue) {
                this.value = "";
                $(this).addClass('focus');
            }
        }
        else {
            if (this.value == this.defaultValue) {
                this.value = "";
                $(this).addClass('focus');
            }
        }
    }).blur(function() {
        if (defaultValue != "") {
            if (!this.value.length) {
                this.value = defaultValue;
                $(this).removeClass('focus');
            }
        }
        else {
            if (!this.value.length) {
                this.value = this.defaultValue;
                $(this).removeClass('focus');
            }
        }


    });
}

