/*Add Eventlistner to the Change Location
var fld = document.getElementById('languageSubmitButton');
if (fld.addEventListener)
	fld.addEventListener('onClick',eventClickformSubmit,false );*/




// Fix background image flickering in IE
try {
  document.execCommand('BackgroundImageCache', false, true);
} catch(e) { }

var close_text = 'close';

// Contact Block layout placeholder
$(function() {
	var $block = $('#ContentChannel .contactBlock');
	if ($block.length > 0) {
		$('body').addClass('contentChannelContactBlock');
		var width = $block.width();
		var height = $block.height();
		var placeholder_div = '<div style="position: relative; z-index: 10; background: #ffffff; width:' + width + 'px; height:' + height + 'px; float: right; display: inline; margin: 0 0 5px 10px;"></div>';
		
		// If we're on a product page, we need to position the placeholder div
		// in such a way that it integrates well with the other bits on the page
		var product_intro = $('#ContentChannel .productIntro');
		if (product_intro.length > 0) {
			var no_images = $('#ContentChannel .productIntro .noImages');
			if (no_images.length > 0) {
				no_images.prepend(placeholder_div);
			} else {
				var media = $('#ContentChannel .productIntro .media');
				if (media.length > 0) {
					media.before(placeholder_div);
				}
			}
		} else {
			// If the contact block overlaps with a section block, it will force down
			// the section block. The extra margin on the li pushes the section block
			// even further down so we just strip it out
			var $section_block = $('#ContentChannel ul.sectionBlock:first');
			if ($section_block.length > 0) {
				if (overlapsVertically($section_block, $block)) {
					$('li:first', $section_block).css( { 'margin-top': 0 } );
				}
			}
			
			// The best for last....if the contact block overlaps with a table in a content
			// block we need to do something magical
			var $content_text_table = $('#ContentChannel div.contentText > table');
			if ($content_text_table.length > 0) {
				if (overlapsVertically($content_text_table, $block)) {
					// Since the table won't wrap around the placeholder div, we need to 
					// reduce the height on the div so that it doesn't overlap with the table
					// anymore. This means that if the table text extends out as far as the
					// contact block, it will be overlapped by the block.
					// Our new height is the difference between the top of the table and
					// the bottom of the contact block, subtracted from the existing block
					// height. The fudge factor is in there to get it as tightly as we can
					// get it. I'm not sure why it's slightly off.
					var new_height = height // height of the contact block
									- (
										$block.position().top // top offset for the block
										+ height // height of the block
										+ parseInt($block.css('margin-top')) // top margin for the block
										+ 2 // fudge factor
										- $content_text_table.position().top // top offset for the table
									);
					// Replace the existing height of the placeholder div with this new height
					placeholder_div = placeholder_div.replace(/height:\d+px;/, 'height:' + new_height + 'px;');
				}
			}
			$('#ContentChannel').prepend(placeholder_div);
		}
	}
});

$(function() {
	if ($.getURLParam('plain_view') == 1) {
		$('html').addClass('plainView');
	}
});

// Detect if an element overlaps vertically with another element
var overlapsVertically = function($elm, $overlaps_with) {
	var elm_position = $elm.position();
	var olap_position = $overlaps_with.position();
	return (elm_position.top < (olap_position.top + fullHeight($overlaps_with)));
}

// Find the full height of an element, including top and bottom margin
var fullHeight = function($elm) {
	var margin_top = parseInt($elm.css('margin-top'));
	var margin_bottom = parseInt($elm.css('margin-bottom'));
	return margin_top + margin_bottom + $elm.height();
}

// Threshold of Wrapper height for showing back to top link.
// If height is less than this, hide the link.
var backToTopHeight = 700;

var activeSection;

/* begin - Navigation Primary */
var NavigationPrimary = {
  init: function() {    
		var c = this;
		var n = $('#NavigationPrimary .content > ul');
		
		if (activeSection != null)
			$('#' + activeSection).addClass('active');
			
		// Use bgiframe to fix dropdowns over selects if it's available.
		$.fn.bgiframe && $('li', n).bgiframe();

		// Mark parent elements so that we can style them with CSS
		$('> li', n).each(function() { c.markParents(this); });
  	
  	// Use the hoverintent plugin if it's available
  	if ($.fn.hoverIntent)
    {
  	  $('li', n).hoverIntent( {
  	    sensitivity: 1,
  	    over: this.mouseenter,
  	    out: this.mouseleave,
  	    timeout: 100
  	  });
    }
  	else
  	  $('> li', n).hover(this.mouseenter, this.mouseleave);

		// Setup Opacity in browser-neutral way
		$(' > li > ul', n).css('opacity', 0.95);
  },
  markParents: function(li) {
    var c = this;
    if ($('> ul', li).size() > 0)
	    $(li).addClass('parent').find('> a').addClass('parent').end().find('> ul li').each( function() { c.markParents(this); });
	},
	mouseenter: function() {
		$(this).addClass('over').children('a').addClass('over');
		// Set a width for menus in IE so that they display right and are just long enough for the longest item
		if ($.browser.msie && ! $(this).is('.widthSet')) {
			var width = 0;
			$('li', this).each( function() {
				if ($(this).width() > width)
					width = $(this).width() + 5;
			});
			width = width + "px";
			$('li', this).each( function() { $(this).css("width", width).children('a').css("width", width); });
			$(this).addClass('widthSet');
		}
	},
	mouseleave: function() { $(this).removeClass('over').children('a').removeClass('over'); }
	
};
$(function() { NavigationPrimary.init(); });
/* end - Primary Navigation */

/* Fix PNGs with alpha transparencies to display correctly in IE6 */
jQuery(function() {
  if ($.fn.pngfix)
  {
    $('#NavigationPrimary, #Footer .channel').pngfix();
  }
});

// Hide "Back to top" link if the page isn't long enough to warrant displaying it.
var BackToTop = {
	init: function() {
		if ($('#Wrapper').height() < backToTopHeight)
			$('#BackToTop').hide();
	}
};
$(function() { BackToTop.init(); });

/* Special search behavior */
var Search = {
  prompt: "Search", // default value - should get real value from markup
  init: function() { this.prompt = $('#qt').focus(this.focus).blur(this.blur).val(); },
  focus: function() { if (this.value == Search.prompt) { this.value = ''; } },
  blur: function() { if (this.value.length == 0) { this.value = Search.prompt; } }
};

$(function() { Search.init(); });

var ProductMediaControl = {
	carousel: null,
	mediaContainer: null,
	label: null,
	imageNumTag: null,
	viewLargerLink: null,
	prompt: 'View more images: ', // Editable by setting ProductMediaControl.prompt after library.js is loaded
	init: function() {
		if (! $.fn.jcarousel)
			return;
			
		var t = this;
		t.mediaContainer = $('.productIntro > .media');
		if (t.mediaContainer.length == 0) {
			return;
		}
		t.carousel = $('ul.images', t.mediaContainer);
		t.label = $('p.label', t.mediaContainer);
		t.modalDialog = null;
		$('li.hideOnLoad', ProductMediaControl.mediaContainer).removeClass('hideOnLoad');
		t.carousel.jcarousel({
			scroll: 1,
			initCallback: t.carouselInitCallback,
			itemVisibleInCallback: t.carouselItemVisibleInCallback,
			animation: 0,
			buttonNextHTML: null,
			buttonPrevHTML: null,
			visible: 1,
			wrap: 'both'
		});
	},
	carouselInitCallback: function(carousel) {
		var PMC = ProductMediaControl;
		PMC.viewLargerLink = $('a.view-larger', PMC.mediaContainer);

		// Only setup label and next/prev controls if we have multiple
		// images.
		if (carousel.size() > 1) {
			PMC.label.html(PMC.prompt + '<span class="imageNum">1</span>/' + carousel.size());
			PMC.imageNumTag = $('span.imageNum', PMC.label);
			$('a.jcarousel-next', PMC.mediaContainer).bind('click', function() {
				carousel.next();
				return false;
			});
			$('a.jcarousel-prev', PMC.mediaContainer).bind('click', function() {
				carousel.prev();
				return false;
			});
			$('p.label,ul.controls li', PMC.mediaContainer).show();
		} else {
			// Hide label and next/prev controls, but not view larger
			// We might have a single image that still has a view larger option.
			$('p.label,ul.controls li', PMC.mediaContainer).hide();
		}
		
		PMC.viewLargerLink.facebox({
			opacity: 0.5,
			loadingImage: '/images/common/loading.gif',
			modalId: 'ProductMediaModal',
			contentSelector: '.channel .content',
			faceboxHtml: '\
	    <div id="ProductMediaModal" style="display:none;"> \
				<div class="popup"> \
		      <div class="header"> \
						<div class="content"> \
							<a href="#" class="close">' + close_text + '</a> \
						</div> \
					</div> \
					<div class="channel"> \
						<div class="content"> \
						</div> \
					</div> \
					<div class="footer"> \
						<div class="content"> \
						</div> \
					</div> \
				</div> \
	    </div>'
		});
	},
	carouselItemVisibleInCallback: function(carousel, li, i, state) {
		if (ProductMediaControl.imageNumTag)
			ProductMediaControl.imageNumTag.html(i);
		ProductMediaControl.setViewLarger(li);
		return false;
	},
	clickViewLarger: function() {
		return false;
	},
	setViewLarger: function(li) {
		var largerImage = $('img', li).metadata().largerImage;
		if (largerImage) {
			ProductMediaControl.viewLargerLink.parent().show();
			ProductMediaControl.viewLargerLink.css( { 'background-position': '100% 0', 'cursor': 'pointer' } );
			ProductMediaControl.viewLargerLink.attr('href', largerImage);
		}
		else {
			ProductMediaControl.viewLargerLink.parent().hide();
			ProductMediaControl.viewLargerLink.css( { 'background-position': '100% -50px', 'cursor': 'default' } );
			ProductMediaControl.viewLargerLink.attr('href', '#');
		}
	}
};
$(function() { ProductMediaControl.init(); });

var SolutionMediaControl = {
	mediaContainer: null,
	viewLargerLink: null,
	init: function() {
		var t = this;
		t.mediaContainer = $('.solutionIntro > .media');
		if (t.mediaContainer.length == 0) {
			return;
		}
		t.modalDialog = null;
		$('ul.controls', t.mediaContainer).show();
		t.viewLargerLink = $('a.view-larger', t.mediaContainer);
		t.viewLargerLink.facebox({
			opacity: 0.5,
			loadingImage: '/images/common/loading.gif',
			modalId: 'ProductMediaModal',
			contentSelector: '.channel .content',
			faceboxHtml: '\
	    <div id="ProductMediaModal" style="display:none;"> \
				<div class="popup"> \
		      <div class="header"> \
						<div class="content"> \
							<a href="#" class="close" onclick="return false;">' + close_text + '</a> \
						</div> \
					</div> \
					<div class="channel"> \
						<div class="content"> \
						</div> \
					</div> \
					<div class="footer"> \
						<div class="content"> \
						</div> \
					</div> \
				</div> \
	    </div>'
		});
		t.setViewLarger($('li:first', t.mediaContainer));
	},
	clickViewLarger: function() {
		return false;
	},
	setViewLarger: function(li) {
		var largerImage = $('img', li).metadata().largerImage;
		if (largerImage) {
			SolutionMediaControl.viewLargerLink.parent().show();
			SolutionMediaControl.viewLargerLink.css( { 'background-position': '100% 0', 'cursor': 'pointer' } );
			SolutionMediaControl.viewLargerLink.attr('href', largerImage);
		}
		else {
			SolutionMediaControl.viewLargerLink.parent().hide();
			SolutionMediaControl.viewLargerLink.css( { 'background-position': '100% -50px', 'cursor': 'default' } );
			SolutionMediaControl.viewLargerLink.attr('href', '#');
		}
	}
};




$(function() { SolutionMediaControl.init(); });

$(function() {
		$('a.newWindow').popupwindow();
    $('#PrintLink').popupwindow(); // Make the print page link open in a new window
    $('#ContentChannel a').printPage(); // Footnote the content
  });

$(document).ready(function() {
	
	// Hide/show the language change block
	 $('.language a').click( function() {
		var $$ = $('#LanguageChange');
		if ($$.is(':visible'))
			$$.hide(); // Let second click on link close interface
		else
			$$.show();
	 });
	 $('#LanguageChange a.close').click( function() { $('#LanguageChange').hide(); } );

	 /* Display JS alert when the 'Go' button is clicked in the language box and no language has been selected. */
	$('#LanguageChange input.languageSubmit').click( function() {
		if (document.getElementById("locationSelector").value == "")
		{
			alert("Please select a language.");
			return false;
		}	
		else
		{
			var v = document.getElementById("locationSelector").options[document.getElementById("locationSelector").selectedIndex].value;
			
			
			if(document.getElementById("remember_me").checked==true){
			
				document.getElementById("Change").action = 'http://www.polycom.com/plantCookie.html?select='+ v +'&remember_me=on';
				
			}
			else
			{
				if(v == 'us_en')
				{
					document.getElementById("Change").action = countryArray[v] + '?showme=y'; // US home page to pass the cookie test
					document.getElementById("Change").method = 'post'
				}
				
				else
					if(v == 'jp_ja')
				{
						document.getElementById("Change").method = 'get';
						document.getElementById("Change").action = countryArray[v];
				}
				else
				{
					document.getElementById("Change").action = countryArray[v];
					document.getElementById("Change").method = 'post'
				}

				
			}

			
			
			document.getElementById("Change").submit;
		}
	 });

 	  

});


  
 

/* Re-sizing solution for the right channel rich media content block on the product details template. */
var rhsFlashDivHeight = "";

function changecss(element, property, value) {
	$(element).css(property, value); 
}

var _hbPageView = function() {
	// Stub for development
	return null;
};

var flash_popup = function(swfName, title, width, height, tagline, domain) {
	//alert("swf: " + swfName);
	//alert("title: " + title);
	//alert("width: " + width);
	//alert("height: " + height);
	//alert("tagline: " + tagline);
	//alert("domain: " + domain);

	jQuery.facebox( { ajax: swfName });
	//jQuery.facebox(function($) { 
	//	$(this).get(swfName, function(data) { $.facebox(data) })
	//})
};

function initialiseRHSFlashDiv()
{
	changecss('#rightnav #rhs_flash_navi', 'height', rhsFlashDivHeight);
	
}
/* End re-sizing JS solution */


function openProductfinderhref(url)
{
	var myheight = 958;
	var mywidth = 950;
	if((url.indexOf("/product_finder/wireless/index.html") > -1))
	{
		myheight =525 ;
		mywidth = 675 ;
	}

	window.open(url,'SelectProduct','height='+myheight+',width='+mywidth+',menubar=0, toolbar = 0, resizable=1,location=1,scrollbars=1');
	return false;
}

/* image swap over */
function MM_swapImgRestore() { 
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_swapImage() { 
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_findObj(n, d) { //v4.01
  var p,i,x;  
	if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
	}
  if(!(x=d[n])&&d.all) 
		x=d.all[n]; 
	for (i=0;!x&&i<d.forms.length;i++) 
		x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
		x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) 
		x=d.getElementById(n); 
	return x;
}

function ActionDeterminator(formName, buttonGrp)
{

        var formaction = 'http://polycom.links.channelintelligence.com/pages/prices.asp?nRGID=2114&sCT=PCOM_WEBSITE_PROD&';
        if(document.forms[formName] == null || document.forms[formName].elements[buttonGrp] == null)
               return true;
        var radioGrp = document.forms[formName].elements[buttonGrp];
        for(i=0; i < radioGrp.length; i++){
               if (radioGrp[i].checked == true) {
                       var radioValue = radioGrp[i].value;
                       document.forms[formName].action = formaction + 'sSKU='+radioValue;
               
               }
        }

        return true;
}

// Support Document Translations
var SupportTranslations = {
	init: function() {
		$('select.translations').bind('change', function(e) {
			var selected_index = this.selectedIndex;
			var option = this.options[selected_index];
			if (option.value == '') 
				return;
			_hbDownload(option.value); //HBX tracking for the document.
			window.open(option.value);
		});
	}
};
$(function() { SupportTranslations.init(); });


/* Tooltips */
(function($) {
	$.fn.languageTooltip = function(options){
		var settings 	= $.extend({
				title: 	'in English',
				xOffset: 10,
				yOffset: 20,
				id: 'ToolTip'
		}, options);

		return this
			.attr('title', settings.title)
			.hover(
				function(e) {
					this.t = this.title;
					if (this.t == "undefined")
							this.t = settings.title;
					this.title = "";
					$("body").append("<p id='" + settings.id + "'>"+ this.t +"</p>");
					$("#" + settings.id)
						.css("top",(e.pageY - settings.xOffset) + "px")
						.css("left",(e.pageX + settings.yOffset) + "px")
						.fadeIn("fast");
				},
				function(e) {
					this.title = this.t;
					$("#" + settings.id).remove();
				}
			)
			.mousemove(function(e) {
				$("#" + settings.id)
					.css("top",(e.pageY - settings.xOffset) + "px")
					.css("left",(e.pageX + settings.yOffset) + "px");
			});
	}
})(jQuery);


function eventClickformSubmit(e){

	alert("hi");
}

function getQVar(urlVarName) 
{
	//divide the URL in half at the '?'
	var urlHalves = String(document.location).split('?');
	var urlVarValue = '';
	if(urlHalves[1]){
				//load all the name/value pairs into an array
		var urlVars = urlHalves[1].split('&');
			//loop over the list, and find the specified url variable
		for(i=0; i<=(urlVars.length); i++){
			if(urlVars[i]){
				//load the name/value pair into an array
				var urlVarPair = urlVars[i].split('=');
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
	//I found a variable that matches, load it's value into the return variable
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}


/* Polycom flash file include */
var JSFile = '/global/javascript/flashpolycom.js';
document.write('<script language="JavaScript" src="'+JSFile+'"></script>');

