$(document).ready(function() {
	// Slide
	$("#menu > li > a.expanded + ul").slideToggle("medium");
	$("#menu > li > a").click(function() {
		$(this).toggleClass("expanded").toggleClass("collapsed").find("+ ul").slideToggle("medium");
	});
	//Carousel paging
    $('.prod_images').cycle(
    {
      pager:'.carousel-nav-inside',
      pagerEvent:'mouseover.cycle',
      pause:6,
      pauseOnPagerHover:1
    })
	//Default Action
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content
	//On Click Event
	$("ul.tabs li").click(function() {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$(activeTab).fadeIn(100); //Fade in the active content
		return false;
	});
	//Examples of how to assign the ColorBox event to elements
    $(".loginlink").colorbox({width:"790", height:"600", iframe:false});
    $(".registerlink").colorbox({width:"790", height:"1200", iframe:false});
    $(".buyNowBtn").colorbox({width:"900", height:"600", iframe:false});
    $(".WriteComment").colorbox({width:"700", height:"500", iframe:false});
    $("a[rel='ProductImage']").colorbox();
    $("a[rel='ReviewPopup']").colorbox();
    $(".Youtube").colorbox({inline:true, innerWidth:425, innerHeight:344, href:"#Video"});
    $(".CExpertVideo").colorbox({inline:true, innerWidth:425, innerHeight:344, href:"#ExpertVideo"});
    $(".CShoppingQueenVideo").colorbox({inline:true, innerWidth:425, innerHeight:344, href:"#ShoppingQueenVideo"});
    $(".CGadgetManiacVideo").colorbox({inline:true, innerWidth:425, innerHeight:344, href:"#GadgetManiacVideo"});
    $(".CTabsVideo").colorbox({inline:true, innerWidth:425, innerHeight:344, href:"#TabVideo"});
    $(".AdvSearch").colorbox({inline:true, innerWidth:540, innerHeight:210, href:"#AdvancedSearchContainer"});
	//Example of preserving a JavaScript event for inline calls.
	$("#click").click(function(){ 
		$('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here.");
		return false;
	});
    var url = document.location.href;
		if(url.search(/\?logErr/i) !== -1){
			$('.login1').colorbox(
				{
					href:"/myprofile/login.jsp", 
					title:"", 
					open: true,
					'onComplete' : $.fn.colorbox.resize()	
				});
		}
		if(url.search(/\?regErr/i) !== -1){
			$('.login2').colorbox(
				{
					href:"/myprofile/registration/registration.jsp", 
					title:"", 
					open: true,
					 'onComplete' : $.fn.colorbox.resize()	
				});
		}
		if(url.search(/\?regSSO/i) !== -1){
			$('.login2').colorbox(
				{
					href:"/myprofile/registration/registration_SSO.jsp?"+url.split("?")[1], 
					title:"", 
					open: true,
					 'onComplete' : $.fn.colorbox.resize()	
				});
		}
		
		if(url.search(/\?forgotpwErr/i) !== -1){
			$(this).colorbox(
				{
						href:"/myprofile/resetPassword/forgottenPassword.jsp", 
						title:"", 
						open: true,
						 'onComplete' : $.fn.colorbox.resize()	
				});
		}
    MakeVideo();
    SearchBox();
    initRSS();
    staticNav();
});
/*# AVOID COLLISIONS #*/
//if(jQuery) (function($){
/*# AVOID COLLISIONS #*/
function initRSS() {
		// if either control exists
		if ($('#feed-control').length > 0 || $('#feed-control2').length > 0) {
			var s = document.createElement('script');
		    s.type = 'text/javascript';
			s.src = 'http://pipes.yahoo.com/pipes/pipe.run?_id=00c4871bab82cd9f40da7ef8599b7549&_render=json&_callback=GetRSS';
			document.getElementsByTagName("head")[0].appendChild(s);
		}
	};
function GetRSS(data) {
		$('#feed-control2').html('');
		var control_1_html = '<div class="feedSource"><ul>';
		// 
		for(var i=0;i<data.value.items.length;i++) {
			// do something to add the item
			// now display it
			$('#feed-control2').append('<li>' + data.value.items[i].title + '</li>');
			control_1_html += '<li>' + data.value.items[i].title + '</li>';				
		}
		control_1_html += '</ul></div>';
		$('#feed-control').html(control_1_html);
        $('.feedSource').jCarouselLite({
			'auto' : 3500,
            'vertical' : true,
            'circular' : true,
            'speed' :300,
            'visible' : 1,
            'beforeStart' : function(el){
            	var next = $(el).next();
                if(next == null) next = $(el).siblings()[0];
                	next.css('opacity', 0);
				},
			    'afterEnd' : function(el){
            		$(el).animate({ 'opacity' : 1 }, 200);
				}
		});
	};
function gototab2 () {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$("#tab2").addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		//var activeTab = $("#tab3").find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$("#tab2").fadeIn(); //Fade in the active content
		return false;
	};
function gototab3 () {
		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$("#tab3").addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content
		//var activeTab = $("#tab3").find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
		$("#tab3").fadeIn(); //Fade in the active content
		return false;
	};
function staticNav() {
        var sidenavHeight = $("#leftColumn").height(); //Get height of left menu
        var winHeight = $(window).height(); //Get height of viewport
        if (sidenavHeight > winHeight) { //If sidenav is taller than viewport...
            $("#leftColumn").css({'position' : 'static'}); //switch the fixed positioning to static. Say good bye to sticky menu!
        } else {
            $("#leftColumn").css({'position' : 'fixed'}); // Or turn it back to the sticky thing
        }
    };
function MakeVideo() {
		$('.movieContainer').each(function(){
			swfobject.embedSWF(
				$(this).html(), 
				this.id, 
				parseInt($(this).css('width')), 
				parseInt($(this).css('height')), 
				"9", 
				null, 
				null, 
				{ 
					wmode: "transparent", 
					loop:false, 
					autoPlay:true 
				},
				{
					allowScriptAccess: "always"	
				}
			);							   
		});
	};
function SearchBox() {
		$('#searchexpanded').hide();
		// open the searchbox if it gets the focus
		$('input.leftSearchInput').click(function(){
			$('#search').hide();
			$('#searchexpanded').show();
            $('#menu').css({"margin-top":"42px"});
			$('#searchexpanded input[name=searchexpanded]').focus();
			$('#searchexpanded input[name=searchexpanded]').val('');
			return false;
		});
        $('span.leftSearchInput').click(function(){
			$('#search').hide();
			$('#searchexpanded').show();
            $('#menu').css({"margin-top":"42px"});
			$('#searchexpanded input[name=searchexpanded]').focus();
			$('#searchexpanded input[name=searchexpanded]').val('');
			return false;
		});
		// any click on the body closes the searchbox
		$(document).click(function(event) {
			var searchParent = $(event.target).parents('div.search-expanded');
			if(searchParent.length == 0){
				$("#searchexpanded").hide();
                $('#menu').css({"margin-top":"0px"});
				$('#search').show();
			}
		});
	};
function initComparableItems() {
		// a maximum of 4 items can be compared. lock other ritems if this maximum is reached 
		$('input.compareCheckbox').click(function() {
			var checks = $('input.compareCheckbox');
			var no_checked = checks.filter(':checked').size();
			if (document.getElementById("chosenNumber")){
			document.getElementById("chosenNumber").innerHTML = no_checked;
			}
			if (document.getElementById("chosenNumber1")){
			document.getElementById("chosenNumber1").innerHTML = no_checked;
			}
			if($(this).attr('checked') &&
			   no_checked >= 3) {
				checks.filter(':not(:checked)').attr('disabled', 'disabled');
			} else {
				checks.removeAttr('disabled');
			}
		});
	};
function initComparableItemsButton() {};
function clearCheckboxes(){
	if(document.ProductsForm){
        for (i=0;i<document.ProductsForm.elements.length;i++)
        {
            if (document.ProductsForm.elements[i].name == 'compareCheckbox')
            {
                document.ProductsForm.elements[i].checked = false;
                document.ProductsForm.elements[i].removeAttribute('disabled');
            }
        }
     }
    };
function initAddressBook(){
		$('input.address-toggler').click(function(){
			toggleAddressType(this);
		});
		$('input[name="address-gr"]').change(function(){
			$('input[name="address-hidden"]').val($(this).val());
			if($(this).val()=='addressType.personal'){
				$('#bsaddress').slideUp('normal');
				$('#haddress').slideDown('normal');
			}
			else{
				$('#haddress').slideUp('normal');
				$('#bsaddress').slideDown('normal');
			}
		});		
	};
function toggleAddressType(selector){
     		var container = $(selector).parents('.address-section'),
     			fieldsets = container.find('fieldset.hidden'),
     			addressType = $(selector).val(),
     			businessSections = container.find('div.business');
     		if(fieldsets.length != 0){
     			if(addressType == 'addressType.personal'){
     				businessSections.hide();
     			}
     			fieldsets.removeClass('hidden');
     		}
     		container.find('fieldset').show();
     		if(addressType == 'addressType.personal'){
     			businessSections.slideUp('normal');
     			container.find('.business .required').addClass('hadRequired').removeClass('required');
     		}
     		else{
     			businessSections.slideDown('normal');
     			container.find('.business .hadRequired').addClass('required').removeClass('hadRequired');
     		}
     		$('input[name="address-hidden"]').val($(this).val());
     	};
         //SearchBox();
/*
      function formValidationRules() {
      					password:{required: true, minlength: 6}, password_repeat: {equalTo: "#password"}
      	};
     function initFormValidation(){	
     		if($.validator != undefined){
     			$('form.validate').validate({ rules:(password:{required: true, minlength: 6}, password_repeat: {equalTo: "#password"}) });
     		};
     	};*/
     function initFormPresets(){
     		$('input.preset, textarea.preset').each(function(){
     			$(this).focusin(function(){
     				var el = $(this);
     				if(el.val() == el.attr('title')) { 
     					el.val(''); 
     					el.removeClass('hint');
     				}							
     			});
     			$(this).focusout(function(){
     				var el = $(this);
     				if(el.val() == '') {
     					el.val(el.attr('title')); 
     					el.addClass('hint');
     				} 
     			});
     		 });
     	};
     	// Due to platform restrictions all submit buttons need to be input elements
     	// This function replaces all "<input type="submit..." with "<button type="submit" ..."
     function replaceFormSubmit(){
     		$('input[type="submit"], input[type="button"]').not('.no-replace').each(function(){
     			var input = $(this),
     				button = $('<button type="' + input.attr('type') + '"></button>'),
     				span = $('<span class="inside">' + input.val() + '</span>');
     			// check if this input was converted already
     			if(input.data('converted') != null){
     				return;
     			} else{
     				input.data('converted', true);	
     			}
     			input.after(button);
     			
     			//should not have span for search in sub category search
     			if(input.attr('id')!="subCatSearchbutton"){
     				button.append(span);
     			}     			
     			button.addClass($(this).attr('class').replace(/-/g,' '));
     			button.attr('name', input.attr('name'));
     			button.attr('id', input.attr('id'));
     			button.click(function(){
     				$(this).parent('form').find('button[type=submit]').not(this).remove();					  
     			});
     			// IE needs some extra attention since it won't add 
     			// the input[type=submit] fields to the POST if the form is submitted with a key stroke
     			if($.browser.msie){
     				var hidden = $('<input type="hidden" name="' + input.attr('name') +'" value="' + input.val() +'" >');
     				button.after(hidden);
     			}
     			input.remove();
     		 });
     	};
		
		
		
function initCheckout(){
		var checkoutSteps = $('.checkoutstep');
		if(checkoutSteps.length == 0){
			return;
		}
		var checkLength = checkoutSteps.length;
		
		for(var i=1;i<=checkLength-1;i++) {
			$('#step_' + i+' .step_content ').hide();
			$('#step_' + i+' a ').addClass('right collapse closed');
		}
	/* removed on request of Francis
		// hide all steps except first
		checkoutSteps.not('#step_1').hide();
	*/
	
	
		// hide all checkout step collapse controlls
		var collapseControls = $('.checkout a.collapse');
	/* removed on request of Francis
		collapseControls.hide();
	*/	
		// make the chekout sections collapsable
		collapseControls.click(function(){
			$(this).parents('.checkoutstep').find('.step_content').toggle();
			$(this).toggleClass('closed');
			return false;
		});
		// hide all sections inside the steps
		$('div[id^=section], a[id^=section]').hide();
		// activate the section inside the step if it was selected by a radio input 
		// every element with "class=section" relates to a div section who's id is "section-[radio_id]"
		$('.checkout input.subsection, .checkout a.subsection').click(function(){
			var section = this.id,
				parent = $(this).parents('.checkoutstep');
			// fields that have no-collapse never close sections
			if(!$(this).hasClass('no-collapse')){
				parent.find('div[id^=section]').not('#section-' + section).slideUp();
			}
			$('#section-' + section).slideDown();
		});
		// show the next step button if at least one option has been selected in the current section
		var nextButtons = $('.next');
	/* removed on request of Francis
		nextButtons.hide();
	*/	
		$('.checkoutstep input[type=radio]').click(function(){
			$(this).parents('fieldset').find('.next').show();															
		});
		// show the next step if selected so'
		nextButtons.click(function(){
			var this_step = parseInt($(this).parents('.checkoutstep')[0].id.split('_')[1]),
				nextStep = $('#step_' + (this_step + 1)); 
	/* removed on request of Francis
			nextStep.slideDown();	
			$('#step_' + this_step + ' a.collapse').show();
	*/			
			$.scrollTo(nextStep, 150);
		});
		// each element with class="action" triggers a change in the available form fields
		// the mapping defines what actions shall be taken after a control is activated
		$(".action").click(this.checkoutActions);
		$(".action").change(this.checkoutActions);
		// add a new certificate section if requested so		
		$('.certificate .add').click(function(){
			var el = $(this),
				section = el.parents('.form-item')[0],
				newSection = $(section).clone(true);
			el.hide();
			newSection.find('input').val('');
			$(section).after(newSection);
		});
		//***************************************************************
		// setup the checkout page according to prepopulated form values
		//***************************************************************
		$('.checkout input.subsection:checked').each(function(){
			var section = this.id,
				parent = $(this).parents('.checkoutstep');
			$('#section-' + section).slideDown();
			parent.find('.next').show();
			var this_step = parseInt(parent[0].id.split('_')[1]),
				nextStep = $('#step_' + (this_step + 1)); 
			nextStep.slideDown();	
			$('#step_' + this_step + ' a.collapse').show();
		});
		$('.checkout .action:checked').each(function(){
			checkoutActions(this.id, true);										 
		});
		$('input.address-toggler:checked').each(function(){
			toggleAddressType(this);												
		});
	};
// a set of actions is executed depending on the id of the control or the id parameter passed in
	// isArtificial is true if this function was not ivoked by user action but by the page load.
function checkoutActions(id, isArtificial){
		var control = this.id || id,
			targets = null,
			mapping = 
				{ 
					'deliver_to_address' :                                                         // the id of the target element
					{
							disable : '.pickup, .local',                                // disable all pickup options, disable local payments
							enable : '.shipping, .remote',                                // enable all shipping options, enable remote payments
							check : '.shipping:first',        
							uncheck : '.pickup, #new-delivery-address',
							hide:'',
							show :''
					},
					'collect_from_store' :
					{
							disable : '.shipping, .remote',                                // disable all shipping options, disable remote payments
							enable : '.pickup, .local',                                        // enable all pickup options, enable local payments
							uncheck : '.shipping, #new-delivery-address',
							check : '.pickup:first'
					},
					'bill_as_invoice' :
					{
						uncheck : '#new-invoice-billing-address',
						hide : '#section-new-invoice-billing-address'
					},
					'bill_as_receipt' : 
					{
						uncheck : '#new-receipt-billing-address',
						hide : '#section-new-receipt-billing-address'
					},
					'pinst:checked' : 								// execute these actions if the element is checked
					{
						enable : '#pinst-period'
					},
					'pinst:unchecked' : 							// execute these ections if the element is unchecked
					{
						disable : '#pinst-period'
					},
					'new-delivery-address:checked' :
					{					
						show : '#section-new-delivery-address'
					},
					'new-delivery-address:unchecked' :
					{					
						hide : '#section-new-delivery-address, #delivery-address-fields',
						uncheck : '#addressH-delivery, #addressB-delivery'
					},
					'new-receipt-billing-address:checked' :
					{					
						show : '#section-new-receipt-billing-address'
					},
					'new-receipt-billing-address:unchecked' :
					{					
						hide : '#section-new-receipt-billing-address, #receipt-address-fields',
						uncheck : '#addressH-receipt, #addressB-receipt'
					},
					'new-invoice-billing-address:checked' :
					{
						show : '#section-new-invoice-billing-address'
					},
					'new-invoice-billing-address:unchecked' :
					{                                        
						hide : '#section-new-invoice-billing-address'
					}
				};
		for(selector in mapping){
			if (selector.indexOf(control) != -1){
				var parts = selector.split(':'),
					target = $("#" + control);
				if (parts.length == 1 ||
					(parts[1] == 'checked' && target.is(':checked')) ||
					(parts[1] == 'unchecked' && !target.is(':checked'))
					) {
					targets = mapping[selector];
					break;
				}
			}
		}
		if(targets == null){
			return;
		}
		// HACK: do not change the state of the "new address" checkbox if it was not checked by the user
		if(isArtificial){
		   switch (control){
			   case 'deliver_to_address': targets.uncheck = targets.uncheck.replace('#new-delivery-address',''); break; 
			   case 'bill_as_invoice': targets.uncheck = targets.uncheck.replace('#new-invoice-billing-address',''); break; 
			   case 'bill_as_receipt': targets.uncheck = targets.uncheck.replace('#new-receipt-billing-address',''); break; 
		   }
		}
		if(targets.disable) { $(targets.disable).attr('disabled','disabled'); }
		if(targets.enable) { $(targets.enable).removeAttr('disabled'); }
		if(targets.check) { $(targets.check).attr('checked','checked'); }
		if(targets.uncheck) { $(targets.uncheck).removeAttr('checked'); }
		if(targets.hide) { $(targets.hide).hide(); }
		if(targets.show) { $(targets.show).show(); }
	};
function initNotification(){
		if($('.notifications .checkboxes').length != 0){
			if ($('#sms-check').attr('checked')) {
				$('#sms-number-layer').show();
				$('#sms-number').focus();
			}
			$('#sms-check').change(function() {
				if ($(this).attr('checked')) {
					$('#sms-number-layer').show();
					$('#sms-number').focus();
				}
				else{
					$('#sms-number-layer').hide();
				}
			});
		}
	};
function CountDown(untilDate) {
	$('#timeRemaining').countdown({
		until: toDate,
		timezone: + 3,
		compact: true,
		format: 'H:M:S'
	});
};
$(window).resize(function () { 
        staticNav();
});
/*# AVOID COLLISIONS #*/
//})(jQuery);
/*# AVOID COLLISIONS #*/
function navigateToPage(position,id){
	var styleOfTab = document.getElementById("tab"+position).style.display;
	if(id!=null && styleOfTab=='block'){
		document.location.href=id;
	}
}


	var xmlHttp;
	function changeDynamicUI(host){
		startRequest(host);
	}
	function startRequest(host){	
	  xmlHttp=createXmlHttpRequest();	
	
	  url=host+"/myprofile/updatePersonalInfo.jsp?sid="+Math.random();
	 
	  xmlHttp.open("GET",url,true);
	  xmlHttp.onreadystatechange=handleStateChange;  
	  xmlHttp.send(null);
	}
	function createXmlHttpRequest(){
	//For IE
       if(window.ActiveXObject){
        	xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
       }
	//otherthan IE 
       else if(window.XMLHttpRequest){
                  xmlHttp=new XMLHttpRequest();
       }
       return  xmlHttp;
    }
	function handleStateChange(){ 
	
  		 if(xmlHttp.readyState==4){  
        	if(xmlHttp.status==200){
        		var response = xmlHttp.responseText;  
        		$('#itemCount').html(response.split("||")[0]);
        		var response1 = response.split("||")[1];
        		if(response1.indexOf("true")!=-1){
        				var response = response1.split("&")[1];
        				login = response.split("|")[0];
        				register = response.split("|")[1];
						$('.welcomeUser').html("<p><a onclick=\"$.colorbox({width:'790', height:'450', href:'/myprofile/login.jsp'}); return false;\" class=\"loginlink login1\" href=\"#\">"+login+"</a>&nbsp;-&nbsp;<a onclick=\"$.colorbox({width:'590', height:'1200', href:'/myprofile/registration/registration.jsp'}); return false;\" class=\"registerlink login2\" href=\"#\">"+register+"</a>");	
				}else{					
					$('.welcomeUser').html(response.split("||")[1]);
				}
			}
			else{
        	}
    	 }
 	}


