/**
 * $Id: website.js,v 1.452 2011-03-21 12:57:30 ivan Exp $
 */

voltimum = window.voltimum || {};

(function($){
$(document).ready(function(){
	var checkedForms = '.newsLetterForm,.registerForm,.checkedForm';

	if($.browser.msie){
		voltimum.selectControls=[];
		
		$('select',checkedForms).each(function(i){
			$(this).ieSelectWidth
		    ({
		        containerClassName : 'select-container',
		        overlayClassName : 'select-overlay'
		    });
		});

		$('.select-container').css('width','239px');
		/*$('select',checkedForms).each(function(i){
			var widths={
				companytype:400,
				country:300
			};
			var width = widths[this.name] || $(this).width()
			this.setAttribute('size',Math.min(10,this.length));
			$(this).hide();
			$(this).parent().css({'position':'absolute','border':'#DEDEDE 2px inset','height':'16px'});
			$(this).css({'position':'absolute','top':'20px','left':'-2px','width':width+'px'});
		}).before('<img src="/templates/eurocable/images/dropDownMono.gif" style="float:right;"><input readonly="readonly" type="text" class="formRowControl formRowControlS" />')
		.bind('click',function(){
			$(this).parent().find('input').val($(this).find('option[selected]').text());
			$(this).hide();
			return false;
		}).each(function(i){
			$(this).parent().find('input').val($(this).find('option[selected]').text());
		});
		$('body').bind('click',function(){
			$('select',checkedForms).hide();
		});
		$('.formRowControlS').parent().find('input,img').bind('click',function(){
			$('select',checkedForms).not(this).hide();
			$(this).parent().find('select').not('[disabled]').toggle();
			return false;
		});*/
		
	}
	$('option[value=0]').css({'font-weight':'bold','color':'#F05024'});
	$('.menuItem').bind('mouseover',function(){
		$(this).addClass('menuItemSelected');
	}).bind('mouseout',function(){
		$(this).removeClass('menuItemSelected');
	});
	$('.menuItem').not('.menuItemLogin').bind('click',function(){
		document.location = $(this).find('a').attr('href');
	});

	var logoContainer = $('.leftBottomLinks');    
	var isinmoovement=false;
	var setLogoPosition=function(eventtype){
		if(isinmoovement && eventtype=='scroll'){return false;}
		isinmoovement = true;
		minoffset = $('.leftLangPanel').height()+$('.leftLangPanel').offset().top+38;
		maxoffset=$('#eurocableWrapper').height()-73;
		maxoffset = maxoffset - (logoContainer.height()-31);
		windowheight=$(window).height()+$(window).scrollTop()-50-(logoContainer.height()-31);
		logooffset = Math.min(maxoffset,windowheight);
		logooffset = Math.max(logooffset,minoffset);
		logoContainer.css({top:logooffset+'px'});
			isinmoovement = false;
			logoContainer.show();
		
	};
	setLogoPosition();
	$('.leftLangPanel').css({'marginBottom':logoContainer.height()+'px'});
	
	$(window).bind('resize',function(){
		setLogoPosition();
	});
	var scrollTimeout=false;
	$(window).bind('scroll',function(){
		if(scrollTimeout){
			clearTimeout(scrollTimeout);
		}
		scrollTimeout = setTimeout(function(){
			if(!scrollTimeout){return;}
			setLogoPosition('scroll');
			scrollTimeout = null;
		},10);
		
	});
	
	$('.leftLangPanelCountry').bind('click',function(){
		$(this).next().find('.leftLangPanelCountrySite').toggle();
		setLogoPosition();
	});

	$('.menuItemLogin').bind('click',function(){
	    var closedState = $('.menuItemLoginFormContainer').css('display')=='none';
		$('.menuItemLoginFormContainer').toggle(closedState);
		$(this).toggleClass('menuItemLoginSelected');
		setLogoPosition();
		return false;
	});
	$('.loginFormButton').bind('click',function(){
		$('#form-login').get(0).submit();
	});
	$("input[type=password]",'#form-login,#default-login-form').bind('keydown',function(e){
		if(e.keyCode==13){
			$('#form-login,#default-login-form').get(0).submit();
		}
	});	
	//fixing homepage height
	var sheight=500;
	voltimum.jQuery('.wideContent .rightContent .module').each(function(){
		sheight+=voltimum.jQuery(this).height();
	});
	if(voltimum.jQuery('.wideContent').height()<sheight){
	    voltimum.jQuery('.wideContent').css({height:sheight})
	}
	//National Regulations
	$('.regulationCountryLabel').bind('click',function(){
		var item = $(this).parent();
		var list = $(this).parent().find('.regulationItemList');
		if(item.hasClass('regulationCountryOpened')){
			item.removeClass('regulationCountryOpened');
			list.hide();
		}else{
			item.addClass('regulationCountryOpened');
			list.show();
		}
	});
	$('.regulationItem').bind('click',function(){
		//alert('start download the file');
	});
	//End National Regulations

    /*Media library*/
	var mediaScrollContainer = $('#mediaLibraryItemsscrolled');
	if(mediaScrollContainer.height()>490){
		mediaScrollContainer.css({'height':'490px','overflow':'hidden'}).jScrollPane({ 
		    scrollbarWidth: 16,
		    wheelSpeed:30,
		    showArrows: true
		});		
	}
	mediaScrollContainer.css({'visibility':'visible'});
    $('.mediaLibraryItem','#mediaLibraryItemsscrolled').css('cursor','pointer').bind('click',function(){
        var flashvars_value = $(this).find('[name=videopath]').val();
		try{
		var url=flashvars_value.match(/videoPath=([^&]+)/);
		if(url.length){
			var parts = url[1].split('/');
			var fname = parts[parts.length-1];
			document.location.hash=fname;
		}
        }catch(err){}
        $('.contentMediaTitle','.contentMedia').html($(this).find('.videoTitleHidden').html());
        $('.contentMediaDescription','.contentMedia').html($(this).find('.videoDescriptionHidden').html());
        if ($('.contentMediaPlayer').children('object').length > 0)
        {
        	var flashplayer_html = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="459" height="300" id="flvPlayer" align="middle">'
        		 				  +'<param name="allowScriptAccess" value="sameDomain" />'
        		 				  +'<param name="allowFullScreen" value="false" />'
        		 				  +'<param name="movie" value="/attachments/medialibrary/flvplayer.swf?dummy='+escape(Math.random())+'" />'
        		 				  +'<param name="quality" value="high" />'
        		 				  +'<param name="bgcolor" value="ffffff" />'
        		 				  +'<param name="flashvars" value="'+flashvars_value+'" />'
        		 				  +'<embed src="/attachments/medialibrary/flvplayer.swf?dummy='+escape(Math.random())+'" flashvars="'+flashvars_value+'" quality="high" bgcolor="ffffff" width="459" height="300" name="flvPlayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
        		 				  +'</object>';
        	$('.contentMediaPlayer').html(flashplayer_html);
        }
        else
        {
        	$('.contentMediaPlayer').children('embed').attr('flashvars',flashvars_value);
        	var flashplayer_html = $('<div>').append($('.contentMediaPlayer').children('embed').clone()).remove().html();
        	$('.contentMediaPlayer').html(flashplayer_html);
        }
        return false;
    });
    if(document.location.hash.length>1){
	    $('.mediaLibraryItem','#mediaLibraryItemsscrolled').each(function(){
	    	var link = $(this).find('[name=videopath]').val();
	    	if(link.split(document.location.hash.slice(1)).length>1){
	    		$(this).click();
	    	}
	    });
    }
    $('.formRowSubmit','.formContainer').bind('click',function(){
        $(this).parents('form').submit();
    });
	$('.newsItem,.listItem').not('.mediaLibraryItem').not('.faqItem').not('.cemacItem').not('.noLinkProcess').each(function(i){
		var link = $(this).find('a','.newsLink').not('.noLinkProcess').attr('href');
		if(link && ! $(this).find('a','.newsLink').parent().hasClass('noLinkProcess')){
			$(this).css('cursor','pointer').bind('click',function(){
				if($(this).hasClass('mediaLibraryItem')){
					$(this).find('.contentLink').click();
				}else{
					document.location = link;
				}
			});
		}
	});
	
	$('.cemacItem').css('cursor','pointer').bind('click',function(){
		var link = $(this).find('.contentLink a').not('.noLinkProcess').attr('href');
		var newWindow = window.open(link, '_blank');
		newWindow.focus();
		return false;
	});
	$('.cemacItem a').click(function(){
		var link = $(this).attr('href');
		if ($(this).attr('target') == '_blank') {
			var newWindow = window.open(link, '_blank');
			newWindow.focus();
		}
		else {
			document.location = link;
		}
		return false;
	});

	$('span.scroll_to_anchor').click(function(){
		var anchor_name = $(this).attr('class').replace('scroll_to_anchor','').trim();
		$('html,body').animate({scrollTop: $('a[name='+anchor_name+']').parents('.cemacItem').offset().top-35},'slow');
		return false;
	});


	/*newsletter form validation*/
	
	$(checkedForms).find('input[type="radio"]').bind('click',function(){
			$('#company,#companytype',checkedForms).parent().find('select,input')
			.attr('disabled',(this.id=='typePersonal'))
			.parents(".formRow").removeClass('emptyRequired');
	});
	$(checkedForms).bind('submit',function(){
		$('.formRow',this).removeClass('emptyRequired');
		var emptyFields = $('input[value=""],select[value=0],textarea[value=""]',this).not('[disabled]');
		emptyFields.parents(".formRow").addClass('emptyRequired');
		var checkedFields;
		$('.6charsMin',this).each(function(){
			if($(this).val().length<6){
			checkedFields=true;
			$(this).parents(".formRow").addClass('emptyRequired');
			}
		});
		
		/*if ($(this).is('.newsLetterForm')) {
			if ($('input.countryNews:checked').length == 0) {
				checkedFields=true;
				$('#country_news_message').html('Please select at least one news country.');
				$('#country_news_message').show();
			}
			else {
				$('#country_news_message').html('');
				$('#country_news_message').hide();
			}	
		}*/
	
		if(emptyFields.length || checkedFields){
			return false;
		}
	});
	$('input,select,textarea',checkedForms).bind('focus',function(){
		$(this).parents(".formRow").removeClass('emptyRequired');
	});
	
	//if(voltimum.biographies){

	if(typeof voltimum.biographies){
		$(".newsText,.newsArticleText").each(function(){
			var content = $(this).html();
			for(var key in voltimum.biographies){
				if(!voltimum.biographies.hasOwnProperty(key) || key==""){continue;}
				content = content.split(key).join("<span class='hint-box'><span class='hint-word'>"+key+"</span><span class='hint-text'>"+voltimum.biographies[key]+"</span></span>");
			}
			$(this).html(content);
		});
		
	}


	//}

	/*hint box */
	voltimum.hintBox = {
        template: '<table cellpadding="0" cellspacing="0" class="hintBox" border="0">'+
            '<tr>'+
                '<td class="lt"><img src="/templates/eurocable/images/blank.gif"></td>'+
                '<td class="mt"></td>'+
                '<td class="rt"><img src="/templates/eurocable/images/blank.gif"></td>'+
            '</tr>'+
            '<tr>'+
                '<td class="ml">&nbsp;</td>'+
                '<td class="content"></td>'+
                '<td class="mr">&nbsp;</td>'+
            '</tr>'+
            '<tr>'+
                '<td class="lb"><img src="/templates/eurocable/images/blank.gif"></td>'+
                '<td class="mb">&nbsp;</td>'+
                '<td class="rb"><img src="/templates/eurocable/images/blank.gif"></td>'+
            '</tr>'+
        '</table>',
        hints:[],
        processPage:function(){
        	var id,count=1;	
        	$("a",".hint-box").wrap("<span class='contentLink'></span>");
            $('.hint-box').each(function(i){
            	if($(this).find('.hint-word').length){
            		id='hint-w-'+i;
            		voltimum.hintBox.hints[id] = $(this).find('.hint-text').html();
            		$(this).html('<span class="hint-w" id="'+id+'">'+($(this).find('.hint-word').html())+'</span>');
            	}else{
            		id='hint-n-'+i;
            		var index;
            		for(var key in voltimum.hintBox.hints){
            			if(voltimum.hintBox.hints.hasOwnProperty(key)){
            				if(voltimum.hintBox.hints[key] == $(this).html()){
            					//index = $('#'+key).html().match(/\d+/)[0];
            				}
            			}
            		}
	                voltimum.hintBox.hints[id] = $(this).html();
	                $(this).html('<span class="hint-n" id="'+id+'"><span class="hint-brace">(</span><span class="hint-index">'+(index || count)+'</span><span class="hint-brace">)</span></span>');
	                if(!index){count+=1;}
                }
            }).css({'display':'inline'});            
            this.box=$(this.template);

            $('body').append(this.box);
            this.box.find('td').fixpng();
            this.bindHints();
        },
        timeout:null,
        bindHints:function(){
            $('.hint-n,.hint-w').bind('mouseover',function(e){
                if(voltimum.hintBox.timeout){
                    clearTimeout(voltimum.hintBox.timeout);
                }
				if(voltimum.hintBox.id != this.id){
                	voltimum.hintBox.id=this.id;
                	voltimum.hintBox.show(this.id,e);
                }
            }).bind('mouseout',function(){
                voltimum.hintBox.timeout = setTimeout(function(){
                    voltimum.hintBox.hide();
                    voltimum.hintBox.timeout=null;
                },700);
            });
            this.box.bind('mouseover',function(){
            	clearTimeout(voltimum.hintBox.timeout);
            }).bind('mouseout',function(){
                voltimum.hintBox.timeout = setTimeout(function(){
                    voltimum.hintBox.hide();
                    voltimum.hintBox.timeout=null;
                },700);
            });
        },
        show:function(id,e){
        	var container = this.box.find('.content');
            container.html(this.hints[id]);
            var left = e.pageX - 200;
            if(left < 200){left = 200;}
            if(left > 600){left = 600;}
            this.box.show();  
            this.box.css({left:left,top:e.pageY+16});
            
            var _ctop = container.offset().top + 60;
            var _maxtop = $(window).height()+$(window).scrollTop()-container.height()-60;
            var _mintop = $(window).scrollTop();
            if(_ctop > _maxtop){
            	_ctop = _maxtop;
            	this.box.css({top:_ctop});
            }
            if(_ctop < _mintop){
            	_ctop = _mintop;
            	this.box.css({top:_ctop});
            }
            
        },
        hide:function(){
            if(this.box && typeof this.box.hide == 'function'){
                this.box.hide();
                this.id=null;
            }
        },
        box:null
    };
    
    voltimum.hintBox.processPage();
    
	$('a').each(function(){
		if($(this).attr('target') && $(this).attr('target')=="_self"){
			return;
		}
		var link = this.href;
		if(link && link!='#' && link.slice(0,7)!='mailto:' && link.slice(0,10)!='javascript' && link.indexOf(document.domain)==-1){
			this.setAttribute('target','_blank');
		}
		if(link.indexOf("_javascripts2_")!=-1){
			this.setAttribute('target','_blank');
			this.setAttribute('href','#');
			this.className = link.split('_javascripts2_')[1];
			$(this).bind('click',function(e){
				var w = $(this).width()/2;
				var links = this.className.split("_");
					var pos = e.clientX - $(this).offset().left+$(window).scrollLeft();
					if(pos < w){
						window.open(links[0],"_blank");
					}else{
						window.open(links[1],"_blank");
					}
				return false;
			});
		}
	});
	
	/**/
	$('a','.language_link').bind('click',function(){
		var lang = this.id.split('_')[1];
		var site_language = $.cookie('site_language');
        if(lang != site_language){
        	$.cookie('user_language',lang,{ expires: 500 });
      		document.location = document.location;
      	}
      	return false;
	});
	var language_picker = $('#language_picker');
	if(language_picker.length){
		  var user_language = $.cookie('user_language');
		  var site_language = $.cookie('site_language');
		  if(!user_language){
		      $("body").append("<div id='dialog_bg_underpopup'></div>")
	          .find('#dialog_bg_underpopup').css({"height": ($(window).height()*2) + $(window).scrollTop() + "px"});
	          $('html').css({"overflow":"hidden"});
	          var dialog=language_picker.find('#language_picker_window').remove();
	          $("body").append(dialog);
	          dialog.css({left:($(window).width()/2 - dialog.width()/2 )+"px",top:($(window).height()/2 + $(window).scrollTop() - 100 )+"px"}).show();
	          dialog.find('.contentLink').bind('click',function(){
	          	var lang = this.id.split('_')[1];
	          	$.cookie('user_language',lang,{ expires: 500 });
	          	if(lang != site_language){
	          		document.location = document.location;
	          	}
	          	dialog.remove();
	          	$('#dialog_bg_underpopup').remove();
	          	$('html').css({"overflow":"auto"});
	          	return false;
	          });
	          dialog.find('.language_picker_window_close_btn').bind('click',function(){
	          	dialog.remove();
	          	$('#dialog_bg_underpopup').remove();
	          	$('html').css({"overflow":"auto"});
	          });
		  }     
	}
	
		//FAQ

	$('.faqQuestion,.regulationCountry').bind('click',function(){
		$(this).toggleClass('itemsOpened');
		$(this).next().toggle();
	});
	//End FAQ

});
}(voltimum.jQuery));

