﻿

$(document).ready(function () {
    initFileUploads();
    // ------------------------
    // Slider
    //-------------------------
    reactivate();
    $("div.slideBanners").slider({
        auto: true,
        continuous: true,
        pause: getSliderPause()
    });
    $("#Tabs").tabs();

    $("#SearchOptions").hide();
    $("#aSearchOptions").click(function (e) {
        e.preventDefault();
        $("#SearchOptions").toggle();
    });
    //	CalculateTabWidth($("#Tabs #Tablist"), false);
    //	CalculateTabWidth($(".tabs"), true);
    //LoadLoginMenu(600);
    TextBoxFocus();
    $('#btnSearchGeoCode').click(function (e) {
        e.preventDefault();
    });
    $('#GoogleMapNoResult').hide();
    /*This is used when ex. a updatepanel is reloaded */

    prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(EndRequest);
    function EndRequest(sender, args) {
        $(document).AjaxReady();
    }

    HideAndToggleComments();


    LoadTipAndPrint();
    CreateQuestionPage();
});

function postGo(url, params) {
    var $form = $("<form>")
        .attr("method", "post")
        .attr("action", url);
    $.each(params, function (name, value) {
        $("<input type='hidden'>")
            .attr("name", name)
            .attr("value", value)
            .appendTo($form);
    });
    $form.appendTo("body");
    $form.submit();
}

function reactivate() {
	$('.fancyDropdown').selectbox({
		containerClass: 'selectBox',
		inputClass: 'selectInput'
	});
}

function HideAndToggleComments() {
	$('.commentArea').hide();
	$('.commentToggleButton').click(function (e) {
		e.preventDefault();
		$('.commentArea,').toggle();
		window.location.hash = "WriteComments";
	});

	$("a[href='#Comments']").click(function () {
		$('.hideOnToggle').hide();
		$('.commentArea').toggle();
		window.location.hash = "Comments";
	});

	$('.answerArea').hide();
	$('.toggleButton').click(function (e) {
		e.preventDefault();
		$('.answerArea').toggle('slow');
	});
	$('.createThreadArea').hide();
	$('.toggleButton').click(function (e) {
		e.preventDefault();
		$('.createThreadArea').toggle('slow');
	});

	if (window.location.hash == "#Comments" || window.location.hash == "#WriteComments") {
		$('.commentArea').toggle();
	}
}

function getSliderPause() {
	var result = parseInt($('#hfBannerSlidePauseSpeed').attr("value"), 10);
	if (isNaN(result)) {
		result = 5000;
	}
	return result;
}

function TextBoxFocus() {
	$('.search input[type="text"], .searchForm input[type="text"], .queryCompletionSearch input[type="text"]').each(function () {
		$(this).focus(function () {
			if (this.value == this.defaultValue) {
				this.value = '';
			}
			if (this.value != this.defaultValue) {
				this.select();
			}
		});
		$(this).blur(function () {
		    if ($.trim(this.value) == '') {
				this.value = (this.defaultValue ? this.defaultValue : '');
			}
		});
    });
    $('.searchInputBenefits input[type="text"]').each(function () {
        $(this).focus(function () {
            if (this.value == this.defaultValue) {
                this.value = '';
            }
            if (this.value != this.defaultValue) {
                this.select();
            }
        });
        $(this).unbind('blur');
    });
	$('.googleMaps input[type="text"]').each(function () {
		$(this).focus(function () {
			if (this.value == this.defaultValue) {
				this.value = '';
			}
			if (this.value != this.defaultValue) {
				this.select();
			}
		});
		$(this).blur(function () {
			if ($.trim(this.value) == '') {
				this.value = (this.defaultValue ? this.defaultValue : '');
			}
		});
	});

	//For the Username field in login
	$('.login .leftColumn .txtUserName').each(function () {
		$(this).focus(function () {
			if (this.value == this.defaultValue) {
				this.value = '';
			}
			if (this.value != this.defaultValue) {
				this.select();
			}
		});
		$(this).blur(function () {
			if ($.trim(this.value) == '') {
				this.value = (this.defaultValue ? this.defaultValue : '');
			}
		});
	});

	//For login password etc.
	$('.txtShow').hide();
	$('.txtClear').show();

	$('.txtShow').each(function () {
		$(this).blur(function () {
			if ($.trim(this.value) == '') {
				$(this).prev().show();
				$(this).hide();
			}
		});

	});
	$('.txtClear').each(function () {
		$(this).focus(function () {
			$(this).hide();
			$(this).next().show().focus();
		});
	});
}

// ------------------------
// TabSearch.ascx
//-------------------------
function CalculateTabWidth(container) {
	container.css("width", "100%");
	var containerWidth = container.width();
	var numItems = container.find('li').length;
	var size = 0;
	container.find("li").each(function () {
		size += $(this).width();
	});
	var additionalWidth = (containerWidth - size) / numItems;

	container.find("li").each(function () {
		var width = $(this).width();
		$(this).width(width + additionalWidth);
	});

}

////////////////////////////////////////////
// CreateQuestionPage.aspx
////////////////////////////////////////////
function CreateQuestionPage() {


	var overlayItem = null;
	var delay = 100;
	var currentItem = null;
	$('.categoryButton').each(function () {
		$this = $(this);

		var checked = false;
		var checkbox = $this.find(":checkbox");
		if (checkbox != null) {
			checkbox.hide();
			checked = checkbox.is(':checked');
		}
		var radioButton = $this.find(":radio");
		if (radioButton != null) {
			radioButton.hide();
			checked = radioButton.is(':checked');
			if (checked) {
				currentItem = radioButton;
			}
		}

		if (checked) {
			$this.addClass("selected");
		}
		var overlay = $this.children('.overlay');
		overlay.hide();
		var overlayTimer;
		$this.mouseover(function () {
			if (overlayItem != null) {
				overlayItem.hide();
			}
			overlayItem = overlay;
			$(this).addClass("selected");
			overlay.show();
			if (overlayTimer) {
				clearTimeout(overlayTimer);
				overlayTimer = null;
			}
		});
		$this.mouseout(function () {
			if (!checked) {
				$(this).removeClass("selected");
			}
			overlayTimer = setTimeout(function () { overlay.hide() }, delay);
		});
		$this.click(function () {
			if (checkbox != null) {
				checkbox.attr('checked', !checked);
				checked = checkbox.is(':checked');
			}
			if (radioButton != null) {
				radioButton.attr('checked', !checked);
				checked = radioButton.is(':checked');
			}
			if (currentItem != null) {
				currentItem.removeClass("selected");
			}
			currentItem = $(this);
			$(this).addClass("selected");
			$(this).parents('form').submit();
		});
	});
}
////////////////////////////////////////////
// PageRate.ascx
////////////////////////////////////////////
function Rate(pageId, ratedValue, ratingArea) {
    $.getJSON("/Extensions/Handlers/Rate.ashx", { pageId: pageId, ratedValue: ratedValue }, function (data) {
		var starClass = data.rate[0].rateValue;
		var rateText = data.rate[0].rateText;
		var ratingContainer = $(ratingArea).find(".rating");
		ratingContainer.removeClass();
		ratingContainer.addClass('rating ' + starClass);
		$(ratingArea).find(".rateInfo").text(rateText);
	});
}

////////////////////////////////////////////
// TipAndPrint.ascx
////////////////////////////////////////////

function LoadTipAndPrint() {

    $('.tipButton').mouseenter(function (e) {
        clearTimeout($(this).data('timeoutId'));
        clearTimeout($('.tipMenu').data('timeoutId2'));
        var offset = $(this).offset();
        var pos = $('.tipButton').position();
        var height = $(this).height();
        var width = $(this).width();
        $('.tipMenu').css({ "left": offset.left - (width * 4) + "px", "top": offset.top + height * 2 + "px" });
        $('.tipMenu').fadeIn('fast');
    }).mouseleave(function () {
        var invoker = this;
        var timeoutId = setTimeout(function () { $('.tipMenu').fadeOut('fast'); }, 1000);
        $(invoker).data('timeoutId', timeoutId); //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
        $('.tipMenu').data('timeoutId2', timeoutId);
    });

	$('.tipMenu').mouseenter(function () {
		clearTimeout($(this).data('timeoutId2'));
		$('.tipMenu').fadeIn('fast');
	}).mouseleave(function () {
		var invoker = this;
		var timeoutId = setTimeout(function () { $('.tipMenu').fadeOut('fast'); }, 1000);
		$(invoker).data('timeoutId2', timeoutId); //set the timeoutId, allowing us to clear this trigger if the mouse comes back over
	});


	$('.emailTip').click(function () {
		$('.tipWindow').fadeIn('fast');
		return false;
	});

	$('.tipClose').click(function () {
		$('.tipWindow').fadeOut('fast');
	});
}

jQuery.fn.extend({
	AjaxReady: function (fn) {
		if (fn) {
			return jQuery.event.add(this[0], "AjaxReady", fn, null);
		} else {
			var ret = jQuery.event.trigger("AjaxReady", null, this[0], false, null);
			// if there was no return value then the even validated correctly
			if (ret === undefined)
				ret = true;
			return ret;
		}
	}
});


/*This is used when ex. a updatepanel is reloaded */
$(document).AjaxReady(function () {
	$('.commentCount').click(function (e) {
		e.preventDefault();
		$('.commentArea').toggle();
	});
});


//PictureUpload validation
function validatePictureUpload(sender, validationCtrl) {
	var fileName = $('input:file').val();
	var fileExtension = fileName.split('.').pop().toLowerCase();
	if (fileExtension == 'jpg' || fileExtension == 'jpeg' || fileExtension == 'png' || fileExtension == 'gif') {
		$(sender).removeAttr('onclick');
		$(sender).click();
	}
	else {
		$(validationCtrl).show();
	}
}

//FileUpload validation
function validateFileUpload(sender, validationCtrl) {
	var fileName = $('input:file').val();
	var fileExtension = fileName.split('.').pop().toLowerCase();
	if (fileExtension == 'jpg' || fileExtension == 'jpeg' || fileExtension == 'png' || fileExtension == 'gif' || fileExtension == 'pdf' || fileExtension == 'doc' || fileExtension == 'docx'
    || fileExtension == 'ppt' || fileExtension == 'pptx' || fileExtension == 'xls' || fileExtension == 'xlsx' || fileExtension == 'txt' || fileExtension == 'bmp' || fileExtension == 'zip') {
		$(sender).removeAttr('onclick');
		$(sender).click();
	}
	else {
		$(validationCtrl).show();
	}
}

function confirmation(sender, msg) {
	var answer = confirm(msg)
	if (answer) {
		$(sender).removeAttr('onclick');
		$(sender).click();
	}
	else {
		return;
	}
}

var W3CDOM = (document.createElement && document.getElementsByTagName);

function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var image = document.createElement('img');
	image.src = '/Templates/Images/Browse.png';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i = 0; i < x.length; i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}

function menuImagesPreloader() {
	var patt = /\"|\'|\)|\(|url/g;
	var images = new Array();
	$('#MainMenu').find('li').each(function (index) {
		//var imageObj = new Image();
		var urlImage = $(this).css('background-image').replace(patt, '');
		//imageObj.src = urlImage;
		images.push(urlImage);
	});

	$(images).each(function (index) {
		var image = new Image();
		image.src = images[index];
	});


}

//Hide EmailTip when done
function hideEmailTipPopUp(form, status, email, name, txtarea, emailfrom) {
	$(form).hide();
	$(status).show();
	$('.mask, .popupWindow').delay(3000).fadeOut('fast');
	$(email).val('');
	$(name).val('');
	$(txtarea).val('');
	$(emailfrom).val('');
	setTimeout(function () { $(form).show(); $(status).hide(); }, 4000);
}

$(function () {
    $('.captionNoJs').attr('class', 'caption');
    $('.slides .slides_container').css('height', '400px');
    $('.slides').slides({
        preload: false,
        generateNextPrev: true,
        generatePagination: false,
        pagination: false,
        animationStart: function (current) {
            $('.caption').animate({
                bottom: -35
            }, 100);
            if (window.console && console.log) {
                // example return of current slide number
                console.log('animationStart on slide: ', current);
            };
        },
        animationComplete: function (current) {
            $('.caption').animate({
                bottom: 0
            }, 200);
            if (window.console && console.log) {
                // example return of current slide number
                console.log('animationComplete on slide: ', current);
            };
        },
        slidesLoaded: function () {
            $('.caption').animate({
                bottom: 0
            }, 200);
        }
    });
    $('.next').text("");
    $('.prev').text("");
});

function showMandatoryStars() {
    $('.mandatory').attr('style', 'display:inline');
}
