// JavaScript Document - Last modified 25/06/09  - Delphine Lepers



function search_model(where){
			var source_data = new Array();
			$.ajax({
				type: "GET",
				url: "/main/_models.xml",
				dataType: "xml",
				success: function(data) {
					$(data).find("m").each(function(){
						source_data.push( $(this).attr("id"));
					});
				$("[id$='"+where+"']").autocomplete({
						source: source_data,
						delay:100,
						minLength:2,
						matchSubset:1,
						maxItemsToShow:10,
						select: function(event, ui) { 
						//it's necessary to set the value to the input for the showModelPage function.
							$('#'+where).val(ui.item.value);
							if(where!='model'){showModelPage(where);};
						}

				});	
				},
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					//alert(errorThrown);
					}
			
		
		});
}

///\brief return the category of a model to show the right KB*/
function getCat(where){
	var theModel = $('#'+ where ).val();
	theModel=theModel.toUpperCase();
	var myRequest=$.ajax({
							url: "/shared/code/SupportWebServs.asmx/getCatPage?site=odw_" + wep.locale + "&m=" + theModel,
							dataType: "xml",
							success:function(xml,data) {
									theURL=xml.getElementsByTagName( 'string' )[0].childNodes[0].nodeValue; 
									$('#support_kb_repair').attr('src',theURL);
									$('#support_kb_repair').show();
							}
							
		});
		
	}

///\brief Go to the product page when we enter a model name*/

function showModelPage(where){
	var theModel = $('#'+ where ).val();
	theModel=theModel.toUpperCase();
	var theURL='';
	var myRequest=$.ajax({
						url: "/shared/code/SupportWebServs.asmx/getModelPage?site=odw_" + wep.locale + "&m=" + theModel,
						dataType: "xml",
						success:function(xml,data) {
							theURL=xml.getElementsByTagName( 'string' )[0].childNodes[0].nodeValue; 
							if(theURL.indexOf('computing/vaio/index')==-1){
								if ($.browser.msie){
									
									var referLink = document.createElement('a');
									referLink.href = theURL;
									document.body.appendChild(referLink);
									referLink.click();
								} else {
									$(location).attr('href',"http://"+document.domain+theURL)
								}
							}else{
								
									$(location).attr('href',theURL)
							};

						}
						
	});
	
;}

function showContactDetails(){
	$('#search_results').toggle(500);
	insert_smartbut();
	}

function getContactDetails(){
	
	var req= $.ajax({
					url:'/contacts/contacts_cic.aspx?site=odw_'+wep.locale,
					success:function(html) {
						$('#search_results').html(html);
/* IF WE ARE ON THE CONTACT PAGE*/
						
						btn_close=$(document.createElement("img")).attr('href','/css/imgs/consumer/ssp-icon-minimize.gif');
						btn_close.attr('id','contact_results_btn');
						btn_close.bind("click",function(e){
								$('#search_results').removeClass('openresults');
								document.location=document.location.href.substring(0,document.location.href.lastIndexOf('#',0));
								$('#search_results').empty();
								btn_close.dispose();
						});
							//Inject the new DOM elements into the results div.
						$('#search_results').after(btn_close).html(html).css('padding','15px');
					},
					//Our request will most likely succeed, but just in case, we'll add an
					//onFailure method which will let the user know what happened.
					onFailure: function() {$('#search_results').text('The request failed.');}
				});

				if(wep.locale=='ro_RO' || wep.locale=='hu_HU' ||wep.locale=='cs_CZ'){
						$('#chat_results').removeClass('hidden');
						insert_smartbut();
						//calling chat.js script
				}
}

///\brief Used in the Product page. Shows the content of a tab box when the tab is clicked.

function activateTab( thisId ) {
		var maxTabs = 6;
		var tabName = new Array( "none", "general", "specifications", "manuals", "compatibility", "repair", "contact" );
		activeTab=tabName[thisId];
		/*This allows Omniture to track the change of tab*/
		s.linkTrackVars="pageName";
		s.pageName = s.prop4 + " : Products : " + model_used + " : "+activeTab;
		s.t(); 
		if($('.tab-active')){$('.tab-active').removeClass('tab-active')};
		$('.tab-box-content').hide();
		$( '#tabTitle_' + thisId ) .addClass('tab-active');
		$( '#section_' + thisId ).show();
		
		switch(thisId){
			case 1 :
			_gaq.push(['_trackPageview', '/general/ModelPage/'+wep.locale+'/'+model_used]);
				break;		
			case 3 :
			_gaq.push(['_trackPageview', '/manuals/ModelPage/'+wep.locale+'/'+model_used]);
				break;		
			case 4 :
			_gaq.push(['_trackPageview', '/compatibility/ModelPage/'+wep.locale+'/'+model_used]);
				break;		
			case 5 :
			_gaq.push(['_trackPageview', '/repair/ModelPage/'+wep.locale+'/'+model_used]);
				break;						
			case 6 : 
				getContactDetails();  
				insert_smartbut();
				_gaq.push(['_trackPageview', '/contacts/ModelPage/'+wep.locale+'/'+model_used]);
				break;
			default : ;
		};
		
}


function getModelManuals( model, lang, mainCat, subCat ) {

	var $theSection = $( "#divManTable" ); 
		if(lang=='sr'){lang='rs'};
		var myRequest = $.ajax({
							   url:"/shared/code/supportwebservs.asmx/getManualsList?cat=" + mainCat + "&subCat=" + subCat + "&model=" + model + "&l=" + lang,
							   success:function(xml) {
								   //FF chops xml results in parts of 4096 octets. Stick them back together
										var r="";
										for (var x = 0;x < xml.getElementsByTagName( 'string' )[0].childNodes.length; x++) {
											r = r + xml.getElementsByTagName( 'string' )[0].childNodes[x].nodeValue;
										}										

										$theSection.html(r);
										document.body.style.cursor='default';
										var thelinks = $('.manual-table a');

										thelinks.each(function(i){
											$(this).attr("target","_blank");
											$(this).bind("click",function(e){
												//pageTracker._trackPageview( '/Manuals/Downloads/' + mainCat + '/' + subCat + '/' + model + '/' + $(this).href );
												_gaq.push(['_trackPageview', '/Manuals/Downloads/' + mainCat + '/' + subCat + '/' + model + '/' + $(this).href]);										
											})		  
										});									
									},
								error: function(XMLHttpRequest, textStatus, errorThrown) {$theSection.html("An error occurred during the treatment");}
							
							});
	}	

function waitImg(){
	var my_img = new Element ( 'img' , { 'src' : '/dl_img/wait.gif'});
	my_img.append($('#divManTable'));
	document.body.style.cursor='wait';
	}
	


///\brief Check the validity of the feedback before sending it - Should be optimised
function sendFeedback( position ) {
	var rating = -1;
	var txtCom = '';
	var txtTab = '';
	var $at = $( '#activeTab' );
	var $os = $("#feedbackLeft option:selected");
	var $os2 = $("#feedbackBottomBox option:selected");
	if ( typeof ActivDiv == 'undefined'){ActivDiv = ""}
	if ( typeof activeTab == 'undefined'){activeTab = ""}
	
	if ( position == 'left' ) {
		var rating = $os.val();
		txtCom = $( '#fbl_txt' ).val(); 
		if ( rating != -1 ) $( '#fbl_txt' ).val('');
	} 
	
	else if ( position == 'bottom' ) {
		var rating = $os2.val();
		txtCom = $( '#fbb_txt2' ).val();
		if ( rating != -1 ) $( '#fbb_txt2' ).val('');
	}

	if ( rating != -1 ) {	
		if ($at) {txtTab = $at.val();}else if((activeTab)){txtTab=activeTab;}else {txtTab="NoTabClicked"};
		storeFBInfoInDB(rating, txtCom, txtTab );
		var $fb = $( '#feedbackBox' );
		var $fbb = $( '#feedbackBottomBox' );
		if($fb) $fb.hide();
		if($fbb) $fbb.hide();
				
	} else {
			var newAlert = $('<div class="alert-content" title="Warning"> '+selectmsg+' </div>');
			$( '#fbl_txt' ).after(newAlert);	
			$(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
	}
	return false;
}

///\brief Function used to store the results of the survey in the database. Not currently used.
function storeSurveyResult(compXp,comments){
	casenr = getUrlVars()["casenr"] ? getUrlVars()["casenr"] : "0";
	supXp = $("input[name='Q2_1']:checked").val();
	compXp = $("input[name='Q2_2']:checked").val();
	comments = $('#survey_commments200').val();
	
	var myRequest = $.ajax({
							url: '/shared/code/supportwebservs.asmx/storeNPSSurveyData?locale=' + wep.locale +'&CaseNumber='+ casenr + "&SupportExperience=" + supXp+'&CompleteExperience='+compXp+'&Comments='+comments,
							success:function(xml){
							var txt = xml.getElementsByTagName( 'boolean' )[0].childNodes[0].nodeValue;
									}
						   });	

	}
	
///\brief Function used to store the results of the repair survey in the database.
function storeRepairSurvey(){
	caseid = $("input[name='Q_caseid']").val();;
	comments = $('#comments').val();
	linkname = $("input[name='Q_linkname']:checked").val();
	var result = new Array();
	

	  for (var i=0; i< 10;i++) {
		  result[i] = $("input[name='Q_" + [i + 1] + "']:checked").val();
		 
		 }
alert(caseid);
	if(linkname=="N"){
		caseid ="";		
	}

alert(caseid);
	var myRequest = $.ajax({
							url: '/shared/code/supportwebservs.asmx/storeRepairSurveyData?locale=' + wep.locale +'&Caseid='+ caseid + '&Q=' + result +'&Comments='+comments,
							success:function(xml){
							var txt = xml.getElementsByTagName( 'boolean' )[0].childNodes[0].nodeValue;
									}
						   });		
	}
		
///\brief Function used to store the results of the nordics NPS survey in the database. 
function storeNPSResult(owner,theRating){
	var myRequest = $.ajax({
							url: '/shared/code/supportwebservs.asmx/storeSurveyData?owner=' + owner + theRating + "&locale=" + wep.locale,
							success:function(xml){
									var txt = xml.getElementsByTagName( 'boolean' )[0].childNodes[0].nodeValue;
									}
						   });
	}

function getUrlVars() {
	var vars = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		vars[key] = value;
	});
	return vars;
}

function faqlaunch(trig, resp){
	var $questions = $(trig);
	var $answers = $(resp);
	$questions.each(function(i){
				$answers.eq(i).hide();
				$(this).css('cursor','pointer');
				var status=0;
				$(this).bind("click",function(e){
					if(status==0){
						$answers.eq(i).show(600);
						$(this).addClass('faq_open');
						status=1;
					//	pageTracker._trackPageview( '/FAQ/'+s.prop2+'/'+model_used+'/'+s.pageName.replace(/\s+/g,'')+'/'+(i+1));
					_gaq.push(['_trackPageview',  '/FAQ/'+s.prop2+'/'+model_used+'/'+s.pageName.replace(/\s+/g,'')+'/'+(i+1)]);
					}else{
						$answers.eq(i).hide(600);
						$(this).removeClass('faq_open');
						status=0;
					}
			});
		});
	}
	
///\brief Sends feedback to the database
function storeFBInfoInDB(theRating, theComments, theActiveTab ) {
	var myRequest = $.ajax({
							url:'/shared/code/supportwebservs.asmx/storeFeedbackData?theLocation=' + escape( document.location ) + '&theRating=' + theRating +'&theComments=' + theComments + '&theActiveTab=' + theActiveTab + '&theModel=',
							success:function(xml){
									var txt = xml.getElementsByTagName( 'boolean' )[0].childNodes[0].nodeValue;
									}
						   });
}


///\brief  Function used in /tvhc/downloads/downloads.aspx?site=odw_fr_BE&f=BDV_v624&m=BDV-E970W

function swapImages( obj, img1, img2, altTxtImg1, altTxtImg2 ){
	
	objImg = obj.src
	currentImg = objImg.substr( objImg.lastIndexOf("/") + 1 );
	
	if ( currentImg == img1 ) {
		obj.src = objImg.substr( 0, objImg.lastIndexOf("/") + 1 ) + img2;
		obj.alt = altTxtImg2;
	} else {
		obj.src = objImg.substr( 0, objImg.lastIndexOf("/") + 1 ) + img1;
		obj.alt = altTxtImg1;
	}
	
}

///\brief  Function used in /tvhc/downloads/downloads.aspx?site=odw_fr_BE&f=BDV_v624&m=BDV-E970W

function showHideSpan( objSpan ){
	
	theSpan = $('#'+objSpan );
	theSpan.toggle();
	}


///\brief  Function used in the hotnews dna/hotnews/hotnews.aspx?site=&m=&f=nwz_s7x_announcement to check serial */

function check_wm_serial(model, serial){
	var affected = "Please contact our Customer Information Center, when the headphones supplied with WALKMAN have these symptoms. Sony will replace the damaged headphones with new ones without charge.";
	var not_affected = "Your WALKMAN is not affected by this issue. You can continue enjoying your WALKMAN.";
	var $wm_message = $("#wm_message");
	
	if (serial.length < 7) $wm_message.html("The serial number must contain 7 digits.");
	else if (model == "NWZ-S738F" && serial >= "5000001" && serial <= "5031355") $wm_message.html(affected);
	else if (model == "NWZ-S739F" && serial >= "5000001" && serial <= "5014255") $wm_message.html(affected);
	else $wm_message.html(not_affected);
}



///\brief Function used in dime/compatibility/dsr/dsr_flash/flash.aspx?site=voe_en_GB_cons&m=DSLR-A200#endofpage*/
function toggleFlashComp( spanObj ){ 
	$('.lensDetails').hide();
	var $theSpan = $('#'+ spanObj );
	$theSpan.css('display') == "block" ? $theSpan.hide() : $theSpan.show();
}	

///\brief   Function used in the downlads pages (cf http://43.221.4.12/dime/downloads/downloads.aspx?site=odw_en_GB&m=HDR-CX7E&f=PMB_V3300 */ 

function dnld(loc){
	if ($('#conditionsbox:checked').val()=='on'){
		if($('#backupsol')) {
			$('#backupsol').show();
			window.open(loc,'mywindow','width=480,height=350');
			return false;
		}else{
			return true;	
		};
		s.pageName="spt : Download page 2 : "+model_used;
		s.t(); 
		

	}else{
			var newAlert = $('<div class="alert-content" title="Warning">'+ agreetxt +'</div>');
			$('#termsandcond_ext').after(newAlert);	
			$(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
		return false;
	};
}

/* added for https files that dont allow to send the parameters..*/
function dnld_https(loc){
	if ($('#conditionsbox:checked').val()=='on'){
		if($('#backupsol')) {
			$('#backupsol').show();
			window.open(loc,'mywindow','width=1200,height=800,scrollbars=yes');
			return false;
		}else{
			return true;	
		};
		s.pageName="spt : Download page 2 : "+model_used;
		s.t(); 
		

	}else{
			var newAlert = $('<div class="alert-content" title="Warning">'+ agreetxt +'</div>');
			$('#termsandcond_ext').after(newAlert);	
			$(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
		return false;
	};
}

///\brief   Function used in the multiple downlads pages (cf http://43.221.4.12/TV/downloads/downloads.aspx?site=odw_de_DE&f=LFA */ 

function dnld_mult(loc,n){
	var $boxes = $('.conditionsboxes');
	//var backups = $('.backupsol');
		if ($boxes[n-1].checked==1){
			window.open(loc,'mywindow','width=430,height=350');
			$('.backupsol').eq(n-1).show();
			return false;
		}else{
			var newAlert = $('<div class="alert-content" title="Warning">'+ agreetxt +'</div>');
			$('#termsandcond_ext').after(newAlert);	
			$(newAlert).MsgAlert({autoClose: true, wait: false, className: 'conditions_warning'});
			return false;
		};
		
}



///\brief   Function used to show or hide sections in the tutorials with buttons and lists of links showing subdivs*/	
function hideAndToggle(){
	
}


///\brief   hides the bif divs in the videotransfer tutorial*/
function hideVideos(){
	
		var $source = $('.togglerVid');
		var $target = $('.toggledVid');	
		
		$source.each( function(i) {
			$target.hide();		
			$(this).css('cursor','pointer');
			var status=0;
			$(this).bind("click",function(e){
					if(status==0){
						$target.eq(i).show();
						$(this).addClass('faq_open');
						status=1;
						//pageTracker._trackPageview( '/FAQ/'+s.prop2+'/'+model_used+'/'+s.pageName.replace(/\s+/g,'')+'/'+(i+1));
						_gaq.push(['_trackPageview', '/FAQ/'+s.prop2+'/'+model_used+'/'+s.pageName.replace(/\s+/g,'')+'/'+(i+1)]);
					}else{
						$target.hide();
						$(this).removeClass();
						status=0;
					}
			});			
		
		});		
	
	}



///\brief  Initiate the value of activDiv- used for the feedback  TO BE RAPPATRIATED
function SetActivDIV(name){ActivDiv = name;}

///\brief  used in that page http://support.sony-europe.com/dime/faq/faq.aspx?site=odw_en_GB&m=DSLR-A200&f=DI_DSLR_A
function showFAQs( theOption, theLanguage ) {

	var theParams = theOption.split( '|' );
	var theLoc	  = 'faq.aspx?site=' + odw + '&sc=' + theParams[0];
	if ( theParams[1] && theParams[1] != '' ) {theLoc += '&m=' + theParams[1];}
	if ( theParams[2] && theParams[2] != '' ) {theLoc += '&f=' + theParams[2];}
	location.href = theLoc;
}




  
function InitTabNav(){
	
	if(!($.browser.version="6.0" && $.browser.msie)){
		try{
			
			var highest=0;
			var $tabs=$('.tab-nav-link span');
			
			$tabs.each(function(i){
				$(this).css('max-width', "350px");	 
				if($(this)[0].offsetHeight > highest){highest=$(this)[0].offsetHeight}
		
			});
			highest=highest-20;
			$tabs.each(function(j){
				$(this).css('height',highest);
	
			});
		}catch(err){return false;}
	}
} 
  
///\brief  Allows to change the language selected on dropdownlist 
function selectLang() {
			var CurrentPage = window.location.href;
			var SiteRepl = $('select#site option:selected').val();							
			
			/* Additionnal check for when a , is added in front of the site parameter */
			if ( CurrentPage.indexOf( "?site=" ) != -1 ) {
								
				reg = /\?site=odw_[a-z]{2}_[A-Z]{2}/i;									
				NewPage = CurrentPage.replace( reg, '?site=' + SiteRepl );														
			}						
			
			$.cookie('site', SiteRepl, {expire: 365});	
				
			window.location = NewPage;
			
}

///\brief  Allows to change the language for countries with several lg 
function changeLANG(){
			var CurrentPage = window.location.href;
			var NewPage;
			var reg;
		
			if (wep.locale=='fr_BE') {var SiteRepl = 'odw_nl_BE';}
			else if (wep.locale=='nl_BE') {var SiteRepl = 'odw_fr_BE';}
			else if (wep.locale=='de_LU') {var SiteRepl = 'odw_fr_LU';}
			else if (wep.locale=='fr_LU') {var SiteRepl = 'odw_de_LU';}
			else if (wep.locale=='de_CH') {var SiteRepl = 'odw_fr_CH';}
			else if (wep.locale=='fr_CH') {var SiteRepl = 'odw_de_CH';}
			
			/* Additionnal check for when a , is added in front of the site parameter */
			if ( CurrentPage.indexOf( "?site=," ) != -1 ) {
				reg = /\?site=,odw_[a-z]{2}_[A-Z]{2}/i;
				NewPage = CurrentPage.replace( reg, '?site=' + SiteRepl );
			}
			else if ( CurrentPage.indexOf( "?site=" ) != -1 ) {
				reg = /\?site=odw_[a-z]{2}_[A-Z]{2}/i;
				NewPage = CurrentPage.replace( reg, '?site=' + SiteRepl );
			}	
			else if ( CurrentPage.indexOf( "&site=" ) != -1 ) {
				reg = /&site=odw_[a-z]{2}_[A-Z]{2}/i;
				NewPage = CurrentPage.replace( reg, '&site=' + SiteRepl );
			}
			else {
				// var NewPage = CurrentPage + "l=" + LangRepl;
				if ( CurrentPage.indexOf( "?" ) != -1 ) {
					NewPage = CurrentPage.replace( "?", "?site=" + SiteRepl + "&" );
				}
				else {
					NewPage = CurrentPage + "?site=" + SiteRepl;
				}
			}
			$.cookie('site', SiteRepl, {expire: 365});
		
			window.location = NewPage;
			}
		
function loadframe(frameId){
 try{
  frame = $('#'+frameId);
  frame.attr('height',window.frames[frameId].document.body.scrollHeight+40);
}
 catch(err){
 }
}
		
// JavaScript Document

function insert_smartbut(){
	switch(wep.locale){
		case 'ro_RO' : imgnr = '21901'; break;
		case 'cs_CZ' : imgnr = '21902'; break;
		case 'hu_HU' : imgnr = '21903'; break;
		default : imgnr = '';
		};
  $('#smartimg').html('&nbsp;<img src="http://rs.instantservice.com/resources/smartbutton/6058/'+imgnr+'/available.gif?' + 
	Math.floor(Math.random()*10001) + '" style="width:0;height:0;visibility:hidden;position:absolute;"' + ' onLoad="agents_available()" onError="agents_not_available()">');
  }
	
function agents_available(){    
	var theChatURL ='';
	odw = location.href.substring(location.href.lastIndexOf('site')+9,location.href.lastIndexOf('site')+14);
	switch(odw){
		case 'ro_RO' : theChatURL = "/contacts/chat/chat.aspx?site=odw_ro_RO"; break;
		case 'cs_CZ' : theChatURL = "/contacts/chat/chat.aspx?site=odw_cs_CZ"; break;
		case 'hu_HU' : theChatURL = "/contacts/chat/chat.aspx?site=odw_hu_HU"; break;
		default : theChatURL = '';
		};
	
	$('#smartbutton').html('<img src="https://admin.instantservice.com/brands/instantservice/images/clickhere.gif" onclick="javascript:window.open(\''+theChatURL+'\',\'_blank\',\'menubar=no, status=no, width=600,height=600\'); return false;">');
return true; } 	

  // IF AGENTS ARE NOT AVAILABLE:
function agents_not_available(){
	
	var theSentence ='';
	switch(wep.locale){
		case 'ro_RO' : theSentence = "Nici un agent nu este disponibil &#238;n acest moment.<br/>Va rugam sa ne trimiteti <a href=\"/contacts/email/email.aspx?site="+ odw +"\">ane-mail</a>.<br/>"; break;
		case 'hu_HU' : theSentence = "Jelenleg minden oper&#225;torunk foglalt.<br/>K&#233;rj&#252;k, k&#252;ldj&#246;n <a href=\"/contacts/email/email.aspx?site="+ odw +"\">emailt.</a><br/>"; break;
		case 'cs_CZ' : theSentence = "Omlouv&#225;me se, ale &#382;&#225;dn&#237; pracovn&#237;ci nejsou moment&#225;lne k dispozici.<br/>Pros&#237;m, za&#353;lete n&#225;m <a href=\"/contacts/email/email.aspx?site="+ odw +"\">e-mail.</a><br/>"; break;
		default : theSentence = '';
		};	
   $('#smartbutton').html(theSentence);
   return true;
  }
	
	
function resizeIframe(height){
	heightnr=parseInt(height)+350+'px';
	if($('#support').length!='0')$('#support').attr('height',heightnr);
	if($('#sparrow').length!='0')$('#sparrow').attr('height',heightnr);
	$('body').hideLoading();

  }


