/*var Royal = {};
Royal.externalLink = false,
Royal.host = location.hostname;*/

$(document).ready(function(){
						   
	$("#catalogRequestForm input[type=text]").each(function(){
		$(this).prev().attr("for", this.id);
	});					   
		//FANCYBOX	
	if($('a.lightbox').length)
	{
		$('a.lightbox').fancybox();
		$('a.lightbox').append("<span class='play-btn'><span>");
	}			   
	if($('.readBio').length)
	{
		$('.readBio').mouseover(function(){
			$(this).parent().parent().find('span').addClass('hover');
		});
		$('.readBio').mouseout(function(){
			$(this).parent().parent().find('span').removeClass('hover');
		});
	}
	
	if($('#productCatalogue').length)
	{
		var currCat = $('#catalogImage img').attr('src');
		$('#productCatalogs li a').hover(function(){
			var catImg = ($(this).attr('rel'));
			var catAlt = ($(this).attr('title'));
			if(catImg != currCat)
			{
			$('#catalogImage img').fadeOut('fast', function(){
			$('#catalogImage').fadeIn().html("<img src='" + catImg + "' alt='" + catAlt + "' />");
			currCat = catImg;
				});
			}else{}
			});
	}
	
	$('#selectAll').click(function(){
		if($('#selectAll').is(":checked"))
		{
			$('.check-boxs input:checkbox').attr('checked', 'true');
			$('#select-all').text('Deselect All');
		}else{
			$('.check-boxs input:checkbox').removeAttr('checked');
			$('#select-all').text('Select All');			
		};
	});
	
	$('.acc-content').hide();	
		$('.trigger:first').addClass('active').next().show();
		$('.trigger').click(function(){
			if( $(this).next().is(':hidden') ) { 
				$('.trigger').removeClass('active').next().slideUp();
				$(this).toggleClass('active').next().slideDown();
			}return false;
		});
		
		if($('#contactForm').length) {
			$.validator.addMethod("NumbersOnly", function(value, element) {
					return this.optional(element) || /^[0-9]+$/i.test(value);
				}, "Field must contain only numbers.");

			$.validator.addMethod("PhoneNumber", function(value, element) {
					return this.optional(element) || /^[0-9\-\+]+$/i.test(value);
				}, "Field must contain a valid phone number, + and -.");

			$.metadata.setType("attr", "validate");

			$('.royalForm').validate();
		}

		if($('#catalogRequestForm').length){
		$.validator.addMethod("NumbersOnly", function(value, element) {
				return this.optional(element) || /^[0-9]+$/i.test(value);
			}, "Field must contain only numbers.");

		$.validator.addMethod("PhoneNumber", function(value, element) {
				return this.optional(element) || /^[0-9\-\+]+$/i.test(value);
			}, "Field must contain a valid phone number, + and -.");

		$.metadata.setType("attr", "validate");

		$('.royalForm').validate();
		}

	/*$('#form1').change(function(){
		var file = $(this).val();
		$('#filename').attr('value', file);
	});*/

	if (!$.browser.opera) {

        $('select.select').each(function(){
            var title = $(this).attr('title');
            if( $('option:selected', this).val() != ''  ) title = $('option:selected',this).text();
            $(this)
                .css({'z-index':10,'opacity':0,'-khtml-appearance':'none'})
                .after('<span class="select">' + title + '</span>')
                .change(function(){
                    val = $('option:selected',this).text();
                    $(this).next().text(val);
                    })
        });

    }
													 
	$('label.overlabel').overlabel();
	$('img[src$=.png]').fixpng();
	$('div.tabpanel>table th h2 a')
		.mouseover(function(){
			var $href = $(this).attr('href');
			var $pane = $(this).parents('div.tabpanel');
			$pane.find('th').removeClass('hover');
			$(this).parents('th').addClass('hover');
			$pane.find('div.panecontent:visible').css('display','none');
			$($href).css('display','block');
		});
	$('div.form-login').append('<span class="corner tleft"></span><span class="corner tright"></span><span class="corner bleft"></span><span class="corner bright"></span>');

	/* search input */
	$("#txt-search").keydown( function(event) {
		if(event.keyCode == 13) {
 		
		event.preventDefault();
	 	event.stopPropagation();
		$("form").submit(function(event) {
			event.preventDefault();
		 	event.stopPropagation();
			return false;
		});
		RedirectUser();
		return false;
	 	}
	 });
	$("#btnSearch").click(function(){ RedirectUser(); });
    $('div.tabpanel>table div.tabpanel-body')
		.each(function(){
		   	var _height = 0;
			$(this).find('>div.panecontent').each(function(){
			    //alert( $(this).height() );
				//_height = (_height>$(this).height())?_height:$(this).height();
			});//.css('height',_height);
		});
	$(".directory td:last-child.space").remove();
	
	/*$('#sel-become').change($emailus_handler);*/
	//$('#sel-become option[value=none]').attr('selected','selected');
	/*$emailus_handler();*/
	
	//this is for exit survey
	/*$("#mainTbl a").each(function() {
		//console.debug("link %o href %s\nclass %s indexOf %d", this, this.href, $(this).attr("class"),this.href.indexOf(Royal.host) );
		if(this.href.indexOf(Royal.host) > -1) {
		  $(this).addClass("internal").bind("click", function(e){
			internal = true;
		  });
		}
		if(this.href.indexOf("mailto") > -1) {
			$(this).addClass("internal").bind("click", function(e){
			internal = true;
		  });
		}
	});*/
	
	if($('.fancybox').length)
	{
	$(".fancybox").fancybox();
	}
		
});

/*function $emailus_handler(){
	if( $('#sel-become').val()=='none' ){
		$('#emailus-form').addClass('hid');
		$('#emailus-disabled').removeClass('hid');
	}else{
		$('#emailus-form').removeClass('hid');
		$('#emailus-disabled').addClass('hid');
	}
};
var internal;
function spawnForm() {
	var loc = location.pathname, newWindow;
	
	if(loc.match(/locator.aspx/gi) ) { // locator survey
		newWindow = window.open('https://www.research.net/jsPopInvite.aspx?sm=YmgsjIqSFYCRpPwpt4IpUg%3d%3d', 'invitationwindow', 'height=300,width=350,scrollbars=yes,resizable=yes,status=yes');
		//alert("locator survey");
		//$("#locatorSurvey").fancybox();
	}
    else {
		newWindow = window.open('https://www.research.net/jsPopInvite.aspx?sm=V7x4D7NcJ%2bPPBmqt0G4Ucg%3d%3d', 'invitationwindow', 'height=300,width=300,scrollbars=yes,resizable=yes,status=yes');
		//alert("all survey");
		//$("#allSurvey").fancybox();
	}
	
}
window.onbeforeunload = function (e) {
  

	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;

//	var internal = $(event.target).hasClass("internal");
	//console.debug("internal %o obj %o hasClass %b internal %b", targ, $(targ), $(targ).hasClass("internal"), internal );
	temp = $(targ);
	
  //if(!internal) { }
  
  if(!internal) {
	  spawnForm();
  }
  
  
};*/

/* =jQuery Plugins*/
(function($){
	/* = plug-in : overlabel */
	$.fn.overlabel = function(options){
		var opts = $.extend( {},$.fn.overlabel.defaults, options );
		var selection = this.filter('label[for]').map(function(){
				var label = $(this);
				var id = label.attr('for');
				var field = $('#'+id);
				if(!field) return;
				var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;
				label.addClass(o.label_class);
				var hide_label = function(){ label.css(o.hide_css) };
				var show_label = function(){ this.value || label.css(o.show_css) };
				$(field)
					.parent().addClass(o.wrapper_class).end()
					.focus(hide_label).blur(show_label).each(hide_label).each(show_label);
				return this;
		});
		return opts.filter ? selection : selection.end();
	};
	$.fn.overlabel.defaults = {
		label_class: 'overlabel-apply',
		wrapper_class: 'overlabel-wrapper',
		hide_css: { 'display': 'none' },
		show_css: { 'display': 'block' },
		filter: false
	};
	/* =plug-in : fix-png */
	$.fn.fixpng = function(){
		var hack = {
			isOldIE: $.browser.msie && $.browser.version < 7,
			filter: function(src){ return "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='"+src+"');"; }
		};
		return this.each(function(){
			if(hack.isOldIE){
				var $$=$(this);
				if($$.attr('src')){
					var span = document.createElement('span');
					$(span).attr({
						id: $$.attr('id'), className: $$.attr('class')
					});
					$(span).css({
						display: 'inline-block', width: $$.width(), height: $$.height(), filter: hack.filter($$.attr('src')), float: $$.attr('align')=='left'?'left':($$.attr('align')=='right'?'right':'none')
					});
					this.outerHTML = span.outerHTML;
				}
			}
		});
	};
	/* =plug-in : equal-heights */
	$.fn.equalizeCols = function(){
		var height = 0,
			 reset = $.browser.msie ? "1%" : "auto";
		return this
			.css("height", reset)
			.each(function() {
				height = Math.max(height, $(this).outerHeight(true));
			})
			.css("height", height)
			.each(function() {
				var h = $(this).outerHeight(true);
				if (h > height) {
					$(this).css("height", height - (h - height));
				};
			});
	};
})(jQuery);

function RedirectUser()
{
    if($('#txt-search').val() != '')
	{
	    var searchUrl = '/Search.aspx?q=' + $('#txt-search').val();
		window.location.href = searchUrl;
    }
}

function getTabsData()
{
    
    var TableStart = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
    var TableEnd = "</table>";
    var objFB = document.getElementById("FB");
    var objTI = document.getElementById("TechnicalInformation");
    var objIG = document.getElementById("ImageGallery");
    var objIGuide = document.getElementById("InstallationGuides");
    var objColors = document.getElementById("COLORS");
    
    var objTable = document.getElementById("tbPanel");
   
    
    
    objTable.style.display = "block";
    
       
    if(objFB != null)
    document.getElementById("features-and-benefits").innerHTML = TableStart +  objFB.innerHTML + TableEnd  ;
    
    if(objTI != null)
    document.getElementById("technical-information").innerHTML = TableStart +  objTI.innerHTML + TableEnd  ;
    
    if(objIG != null)
    document.getElementById("image-gallery").innerHTML = TableStart +  objIG.innerHTML + TableEnd  ;
    
    if(objIGuide != null)
    document.getElementById("installation-guides").innerHTML = TableStart +  objIGuide.innerHTML + TableEnd  ;
    
    if(objColors != null)
    document.getElementById("colors").innerHTML = TableStart +  objColors.innerHTML + TableEnd  ;
    
    
    
   
}


function showVal()
{
var objEmailUs = document.getElementById("emailus-disabled")
var objEmailUsForm = document.getElementById("become-a-dealer");
var objSelect = document.getElementById("sel-become").selectedIndex

    switch(objSelect)
    {
        case 0:
        clearForms();
        objEmailUs.style.display = "block";
        break;
        
        case 1:
         clearForms();
               objEmailUsForm.style.display= "block";
        break;
        
        case 3:
        clearForms();
              document.getElementById("catalogue").style.display="block";
        break;
        
        case 5:
        clearForms();
        document.getElementById("contact-us").style.display="block";
        break;
        
        
        case 6:
         clearForms();
          document.getElementById("feedback").style.display="block";
        break;
       
        
        
    }// end of switch

}// end of function

function clearForms()
{
    if(document.getElementById("emailus-disabled"))
    document.getElementById("emailus-disabled").style.display="none";
    
    if(document.getElementById("catalogue"))
    document.getElementById("catalogue").style.display="none";
    
    if(document.getElementById("become-a-dealer"))
    document.getElementById("become-a-dealer").style.display="none";
    
    if(document.getElementById("feedback"))
    document.getElementById("feedback").style.display="none";
    
    if(document.getElementById("contact-us"))
    document.getElementById("contact-us").style.display="none";
    
}


function showProductImage(obj)
{
    
    window.open("/ProductImageZoom.aspx?name="+obj ,"mywindow","menubar=0,resizable=1,location=0,status=0,scrollbars=1,width=500,height=500")
}

function showHideMenuItems(thisNode, nodeLevel)
{
    nodeLevel = nodeLevel - 2;

    if(thisNode.parentNode.className == "selected"){
       $(thisNode.parentNode).removeClass('selected'); //thisNode.parentNode.className = '';
    }
    else
    {
        try
        {
            if(nodeLevel == 0 && selectedParent != thisNode)
            {
                $(selectedParent.parentNode).removeClass('selected'); //selectedParent.parentNode.className = "";
            }
            if(nodeLevel == 1 && selectedChild != thisNode)
            {
                $(selectedChild.parentNode).removeClass('selected'); //selectedChild.parentNode.className = "";
            }
        }
        catch(e)
        {}

        if(nodeLevel == 0)
        {
            selectedParent = thisNode;
        }
        if(nodeLevel == 1)
        {
            selectedChild = thisNode;
        }

        $(thisNode.parentNode).addClass("selected"); //thisNode.parentNode.className = "selected";
    }
}

var selectedParent = ''
var selectedChild = ''
function InitializeSelectedMenuItems()
{
    selectedParent = document.getElementById('selected_Parent');
    selectedChild = document.getElementById('selected_Child');
}

//////// function to hide show div for order a catalogue

function showDvCatalogue(objShow,objHide)
{
    var objShow = document.getElementById(objShow);
    var objHide = document.getElementById(objHide);
    objHide.style.display = "none";
    objShow.style.display="block";
}

function disableEmail()
{
   if(document.getElementById("emailus-disabled"))
    {
        document.getElementById("emailus-disabled").style.display="none";
    }
}

function getRgForm(obj)
{
    var form_id = obj.options[obj.selectedIndex].value;
    var id="154";
    var path="/ContactUsLandingPage.aspx?id=" + id + "&ekfrm=" + form_id
    window.location.href = path;
}

function SelectForm()
{
    var strParamName = "ekfrm";
    var strReturn = "";
    var strHref = window.location.href;
    if ( strHref.indexOf("?") > -1 )
    {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
        {
            if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 )
            {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }

    for(var i=0; i<document.getElementById('sel-become').options.length; i++)
    {
        if(document.getElementById('sel-become').options[i].value == strReturn)
            document.getElementById('sel-become').options[i].selected = true;
    }
}

function ShowFlashMovie(videoURL, videoTitle, videoDescription, autoPlay)
{
    //document.getElementById("videoTitle").innerHTML = "<strong>" + videoTitle + "</strong>";
    //document.getElementById("videoDescription").innerHTML = videoDescription;

    var so = new SWFObject("/uploadedfiles/swf/vplayer.swf", "tctmd_vplayer", "650", "400", "9", "#FFFFFF", false);

    if(autoPlay.toLowerCase() == "false")
    {
        so.addVariable("autoPlay", "false");
    }
    else
    {
        so.addVariable("autoPlay", "true");
    }

    so.addVariable("startOnMute", "false");
    so.addVariable("volume", "100");
    so.addParam("allowScriptAccess","always");
    so.addParam("allowFullScreen","true");
    so.addParam("wmode", "window");
    so.addVariable("onplayerfinish", "playerfinish");
    so.addVariable("flvPath", videoURL);

    so.write("divSwf");
}

function ShowQuicktimeMovie(videoURL)
{
    QT_WriteOBJECT_XHTML_CUSTOM(videoURL, '650', '400', '', 'autoplay', 'true', 'emb#bgcolor', 'white', 'align', 'middle'); 
}

function ConfirmSubmit()
{
    var x=window.confirm("You are about to update the dealer information. Proceed with the changes?")
    if (x)
        return true;
    else
        return false;
}

function getOrderForm(id)
{
  
    var id="154";
    var path="ContactUsLandingPage.aspx?id=" + id + "&ekfrm=" + id
    window.location.href = path;
}
