var crtFtSz = 1;
$(document).ready(function(){
$("#template_contentBody .asset:last-child").css({backgroundImage:'none'});
	primeNavHoverCtrl();
	primeNavCapsCtrl();
	widgetCtrl();
	fontSizeCtrl();
	agentInfoWidget();
	showPhoneWidgetCtrl();
	initPopLinks();
	langSelect();
	locatorMetrics();
	faqCtrls();
	initializePlanner();	
	initializeCalculators();
	initSlideshow($('.featuredProductWidgetSlides'));
	if($('#infoMatic').length > 0)
	{
	    initInfoMaticTabs();
	}
	initGallery();
	if($('#weatherHeader').length > 0)
	{
	    initWeather();
	}
	if ($('#TXAlert').length > 0) {
	    initTXAlert();
	}
})
function primeNavHoverCtrl(){
	$('#primeNav li').hover(function(){
		$(this).addClass('menuHover');
	}, function() {
		$(this).removeClass('menuHover');
	})
}
function primeNavCapsCtrl(){
	$('#menuFirst').hover(function() {
		$('#template_primeNavLeft').attr('class', 'onLeft');
	}, function() {
		$('#template_primeNavLeft').attr('class', 'offLeft');
	})
	$('#menuLast').hover(function() {
		$('#template_primeNavRight').attr('class', 'onRight');
	}, function() {
		$('#template_primeNavRight').attr('class', 'offRight');
	})
}
function widgetCtrl(){
	$('.sideBarWidgetTitle,.sideBarWidgetSubContantTitle').click(function(){
		$(this).next().slideToggle(300);
		$(this).find('img,span').toggleClass('active');
	})
}
function fontSizeCtrl(){
	$('#fontSizeCtrl').click(function(){
			if(crtFtSz != 2){
				crtFtSz = crtFtSz + 0.5;
				} else {
					crtFtSz = 1;
				}
			$('#template_contentBody').css('fontSize', crtFtSz + 'em');
	});
}
function agentInfoWidget(){
	$('#agentInfoImgLnk').click(function(){
		//$('#agentInfoPop').css("display", "inline");
		$('#agentInfoPop').show(300);
		return false;
	})
	//$('#agentInfoPopCloseBtn').click(function(){
	$('#agentInfoPopHeader').click(function(){
		//$('#agentInfoPop').css("display", "none");
		$('#agentInfoPop').hide(300);
	})
}

function showPhoneWidgetCtrl(){
	var displayPhone = $('#hiddenPhone').html();
		$('#showPhoneWidget').click(function(){
				$(this).html(displayPhone);
				return false;
			})
	var displayFax = $('#hiddenFax').html();
		$('#showFaxWidget').click(function(){
				$(this).html(displayFax);
				return false;
			})
	var displayTollFree = $('#hiddenTollFree').html();
		$('#showTollFreeWidget').click(function(){
				$(this).html(displayTollFree);
				return false;
			})
}
function popWin(content,id){
var popWin = $(
	'<div class="popWinContainer">'+
	'<div class="popWin" id="'+id+'Pop">'+
	'<div class="popWinTopRight"><div class="popWinTopLeft">'+
	'<div class="popWinTopCenter"><div class="popWinCtrls"><span class="popWinCtrl">close <img src="/skins/themes/saphire/images/popWin/closeWindow.gif" width="13" height="12" /></span></div></div>'+
	'</div></div>'+
	'<div class="popWinMiddleRight"><div class="popWinMiddleLeft">'+
	'<div class="popWinMiddleContent">'+$(content).outerHtml()+'</div>'+
	'</div></div>'+
	'<div class="popWinBottomRight"><div class="popWinBottomLeft">'+
	'<div class="popWinBottomCenter"></div>'+
	'</div></div>'+
	'</div></div>'
	);
	maskOver();
	if(id == 'emergencyAlert')
	    belowSaphireContact(popWin);
	else
	    centerToWindow(popWin);
	$('body').append(popWin);
	$(popWin).find('.popWinCtrl').click(function(){
		killMaskOver();
		$(popWin).remove();
	});	
}
function belowSaphireContact(obj){
	$(obj).css({top: $('html').scrollTop()+190+'px'});
}
function maskOver(){
		var mask = $('<div class="maskOver">&nbsp;<div>');
		$(mask).css('height', $(document).height());
		$('body').append(mask);
		stopSlideShow();
}
function killMaskOver(){
		$('.maskOver').remove();
		startSlideShow();
}
function killPopWin(){
	$('.popWin').remove();
}
function initPopLinks(){
		$('.getAQuoteFqLink').click(function(){$.getScript('/skins/themes/saphire/scripts/getAQuoteFq.js');return false;})
	}
function langSelect(){
	$('.language_options').change(function(){
		var destination = $('.language_options option:selected').attr('value');
		if(destination != 'Language'){
			window.location = destination;
		}
		});
}
function locatorMetrics(){
 	$('.result').each(function(){
		var resultId = $(this).attr('id') + '_';
		$(this).find('a').click(function(){
			alert(resultId + $(this).attr('class'));
			return true;
		})
	})
}
function faqCtrls(){
	$('.categoryItem').click(function(){
		$(this).next().slideToggle(300);
		$(this).toggleClass('active');
	})
	$('#expAll').click(function(){
		$('.categoryItem').next(':hidden').slideToggle(300).prev().toggleClass('active');
	})
	$('#clsAll').click(function(){
		$('.categoryItem').next(':visible').slideToggle(300).prev().toggleClass('active');
	})
}
function initializePlanner(){
    $.getScript('/lifePlanner/scripts/LifePlanner.js');
}
function initializeCalculators(){
	$.getScript('/modules/calculators/deductible/scripts/Wizard_1.0.1.js');
}	
function linkAlert(destination){
	$.getScript('/skins/themes/saphire/scripts/linkAlert.js');
	return false;
}
function centerToWindow(obj){
	$(obj).css({top: $('html').scrollTop()+50+'px'});
}
jQuery.fn.outerHtml = function() {
	return $('<div>').append(this).html();
};
// Planner methods
function VM$Utils$ShowLoader(){
    var parent = $('#planerWidget');
    parent.addClass('LIFE_loader_parent');
    var mask = $('<div id="imgPlannerLoaderMask" class="LIFE_loader_mask">&nbsp;</div>')
    var object = $('<img id="imgPlannerLoader" class="LIFE_loader" src="/lifePlanner/images/loader.gif" height="66" width="66" />');
    parent.append(mask);
    mask.width(parent.width());
    mask.height(parent.height());
    parent.append(object);
    var x = (parent.width() - object.width()) / 2;
    var y = (parent.height() - object.height()) / 2;
    object.css({ top:y + 'px', left:x + 'px'});
    mask.show();
    object.show();
}
function VM$Utils$HideLoader(){
    $('#imgPlannerLoaderMask').remove();
    $('#imgPlannerLoader').remove();
}
//Start Featured Product Slideshow
function initSlideshow(parent){
    if(parent.children().length > 1){
        parent.find('> *').hide().filter(':first').show().addClass('selected');
        window.setInterval(function(){
            parent.find('.selected').removeAttr('class').fadeOut(1000,function(){
                if($(this).is(':last-child')){
                    parent.find(':first').fadeIn(1000).addClass('selected');
                }else{
                    $(this).next().fadeIn(1000).addClass('selected');
                }
            });
        },6000);
    }              
}
var slideShowTimer;
var currentSlide;
function initSlideshow(parent){
	if(parent.children().length > 1){
		parent.find('> *').hide().filter(':first').show();
		currentSlide = parent.find(':first');
		runSlideShow();
	}
}
function runSlideShow(){
    slideShowTimer = setInterval(function() {
        currentSlide.fadeOut(1000, function() {
            if ($(this).is(':last-child')) { currentSlide = $(this).parent().find(':first'); } else { currentSlide = $(this).next(); }
            currentSlide.fadeIn(1000).css({ display: 'block' });
        });
    }, 5000);
}
function stopSlideShow(){
    if(currentSlide != null){
	    currentSlide.stop();
	    clearInterval(slideShowTimer);
    }
}
function startSlideShow(){
    if(currentSlide != null){
	    currentSlide.fadeTo('slow',1,function(){runSlideShow();});
    }
}
//End Featured Product Slideshow
function SWFCallGetAQuote(){
	$.getScript('/skins/themes/saphire/scripts/getAQuoteFq.js');
}
//Image Gallery
var currentGalleryId;

function initGallery(){
	$('.assetGalleryImage').each(function(){
		var imgOffset = $(this).offset();
		var imgHeight = $(this).height();
		var parentOffset = $(this).parent().offset();
		var adjOffsetTop = (imgOffset.top - parentOffset.top) + (imgHeight - 15);
		var adjOffsetLeft = (imgOffset.left - parentOffset.left) - 3;
		$(this).parent().css({position:'relative'}).append('<img id="'+$(this).attr('id')+'" class="viewGalleryBtn" src="/skins/widgets/imageGallery/images/viewGalleryBtn.gif" style="position:absolute;left:'+adjOffsetLeft+'px;top:'+adjOffsetTop+'px;z-index:99;cursor:pointer;"/>');
	})
	$('.galleryLink,.viewGalleryBtn').click(function(){
		currentGalleryId = $(this).attr("id");
		//$.getScript('/skins/widgets/imageGallery/scripts/vm.gallery.js');
		vm_insertCss(vm_galleryStyle);
        popWin(vm_GalleryHtml,'gallery');
        vm_getImages();
		return false;
	});
}
//Weather
function initWeather(){
    $.getScript('/skins/widgets/weather/scripts/weather.js');
}
//Gallery Begin
var vm_GalleryHtml = $('<div id="vm_imgGallery"><div class="vm_viewer"></div></div>');
var vm_galleryStyle = '/skins/widgets/imageGallery/css/gallery.css';

function vm_initThumbs(){
		$('.vm_imgThumb').fadeTo('fast',0.25)
		.hover(function(){$(this).fadeTo(300,1);},function(){$(this).fadeTo(300,0.25);})
		.click(function(){
			var objOffset = $(this).offset();
			var parentOffset = $('#vm_imgGallery').offset();
			var newOffetTop = Math.abs(parentOffset.top - objOffset.top);
			var newOffetLeft = Math.abs(parentOffset.left - objOffset.left);
			var newObj = $(this).clone();
			newObj.css({position:'absolute',top:newOffetTop,left:newOffetLeft})
				.attr({title:'Click to Shrink'})
				.appendTo('#vm_imgGallery')
				.animate({top:0,left:0,width:'402px',height:'300px',opacity:1,margin:'0px'},200,function(){
					vm_displayCaption(this);
				})
				.click(function(){
					vm_hideCaption();
					$(this).animate({top:newOffetTop,left:newOffetLeft,width:'78px',height:'58px'},200,function(){
					$(this).remove();
				});
			});
	});
}

function vm_displayCaption(obj){
    if($(obj).attr('alt')){
	    var imgInfo = $('<div class="vm_imgInfo"><div class="vm_imgTitle">'+$(obj).attr('alt')+'</div></div>');
	    if($(obj).attr('imgCaption')){
		    var imgCap = $('<div class="vm_imgCaption">'+$(obj).attr('imgCaption')+'</div>');
		    imgCap.appendTo(imgInfo);
	    }
	    imgInfo.prependTo('#vm_imgGallery');
	    setTimeout(function(){$('.vm_imgCaption').slideUp('300');},800);
	    $('.vm_imgTitle').click(function(){$('.vm_imgCaption').slideToggle(300);});
	}
}

function vm_hideCaption(){$('.vm_imgInfo').remove();}

function vm_getImages(){
		var galleryId = currentGalleryId;
		var clientId = $('#vmContextInformation_siteIdentifier').attr('value');
		var url = '/skins/widgets/imageGallery/services/galleryData.aspx?galleryId='+galleryId+'&siteIdentifier='+clientId;
		$.getJSON(url,vm_gall_processImages);
}

function vm_gall_processImages(data, textStatus){
    if(textStatus == "success"){
    $.each(data.images, function(){
        $('<img class="vm_imgThumb" title="Click to Enlarge"/>')
            .attr('src',this.location)
            .attr('alt',this.alternateText)
            .attr('imgCaption',this.caption)
            .appendTo('.vm_viewer');
        });
    vm_initThumbs();
    }
}

function vm_insertCss(file){$('head').append('<link rel="stylesheet" type="text/css" href="'+file+'" />');}
//Gallery End

function initTXAlert() {
    //    $.getScript('/skins/widgets/emergencyAlert/2009-09-17TX/alert.js');
    $('head').append('<link rel="stylesheet" type="text/css" href="/skins/widgets/emergencyAlert/css/alert.css" />');
    var content = '<div>' +
    //        '<span><b></b></span>' +
    //        '<br/><br/>' +
        "<p>Farmers claims adjusters and agents in El Paso, Texas and surrounding areas are ready to help customers effected by the storms on Sept. 16. Drive-in claims locations are open for storm-damaged vehicle inspections. Appointments are required for inspections, which can be made by calling Farmers HelpPoint&#174; at (800) HELPPOINT - (800) 435-7764.</p>" +
	"You can also visit our Customer Care Vehicle at:<br/>"+
	"K-Mart<br/>"+
	"11330 Montwood Drive<br/>"+
	"El Paso, TX 79936<br/>"+
        '</div>';

    popWin(content, 'emergencyAlert');
}