﻿var imgPassiveDefault = '/site/core/images/nl-doc.png';
var imgActiveDefault = '/site/core/images/nl-doc-full.png';

var imgPassiveInit = imgPassiveDefault;
var imgActiveInit = imgActiveDefault;

var imgPassive = imgPassiveDefault;
var imgActive = imgActiveDefault;

function onLoad(isAdmin){      	   	   
	   setSecondMenuLevel();	  	   
	   $('input[type="file"]').addClass('file_field');  
	   Cufon.now();
	   CufonCallStyles(isAdmin);  
}

function CufonCallStyles(isAdmin){
    if (!isAdmin){        
        Cufon.replace('.bread-header h1', { fontFamily: 'Impact' });  
        Cufon.replace('.rightRTE h1', { fontFamily: 'Impact' });  
	       Cufon.replace('.newsletter h1', { fontFamily: 'Impact' });  	   
	       Cufon.replace('.header_container h1', { fontFamily: 'Impact' });  
	       Cufon.replace('.front-rte-big h1', { fontFamily: 'Myriad Pro' });
	       Cufon.replace('.slogan h1', {fontFamily: 'Myriad Pro' });	   
	   }
}

$(document).ready(function(){
    submitButton();

    $('.pf-navigator div a').click(function(){                    
            stopSlideshow();                    
            var pos = 0;            
            $('.pf-navigator div').removeClass('selected');
            $(this).parent().addClass('selected');
            pos = parseInt($(this).parent().attr('type').substring(9,10));
            showImageWithPosition(pos-1);
            return false;
        }
     );    
     
     newsletterAllFuncions();   
});

function setSecondMenuLevel(){
    var menu_items = $('#negeso_main_menu > li');
    var leftShift = $(menu_items[0]).attr('offsetLeft');
    var eachShift = 0;
    
    for (var i = 0; i < $(menu_items).length; i++){
        eachShift = $(menu_items[i]).attr('offsetLeft') - leftShift;        
        $(menu_items[i]).find ('ul').css('margin-left','-' + eachShift + 'px');
        eachShift = 0;
    }
}

function newsletterAllFuncions(){
    initNewsletterImages(); 
    newsletterEmailInputs();
    newsletterMainShopLocationSelect();
    newsletterTopShopLocationSelect();
    newsletterFrontDocumentsSelect();
	//hideValueSelect();
	openFile();
}

function newsletterEmailInputs(){
     $('.nl_content input:first').focus(function () {
         if ($(this).attr('value') == 'uw emailadres')
            $(this).attr('value','');        
         $('.nl_content input:last').attr('disabled', 'disabled');
     });
     $('.nl_content input:first').focusout(function () {
         if ($(this).attr('value') == ''){
             $(this).attr('value', 'uw emailadres');         
            $('.nl_content input:last').removeAttr('disabled');
         }
     });

     $('.nl_content input:last').focus(function () {
         if ($(this).attr('value') == 'uw emailadres')
             $(this).attr('value', '');                 
         $('.nl_content input:first').attr('disabled', 'disabled');
     });
     $('.nl_content input:last').focusout(function () {
         if ($(this).attr('value') == '') {
             $(this).attr('value', 'uw emailadres');
             $('.nl_content input:first').removeAttr('disabled');
         }
     });      

     $('.newsletter input[type="text"]').focus(function(){                    
        if ($(this).attr('value') == 'uw emailadres')
            $(this).attr('value','');
     });      
     $('.newsletter input[type="text"]').focusout(function(){                    
            if ($(this).attr('value') == '')
                $(this).attr('value','uw emailadres');
     });
}

function initNewsletterImages() {
    if ($('#nlDoc').length > 0) {
        var imageType = '';
        var imageTypePos = '';        
        var imageExists = true;

        var imageCurr = $('#nlDoc img').attr('src');
        $.ajax({
            url: imageCurr,
            async: false,
            type: 'HEAD',
            error: function () {
                imageExists = false;
            }
        });
        
        //init activa and passive images
        if (imageExists) {
            imageTypePos = imageCurr.lastIndexOf('.');
            imageType = imageCurr.substring(imageTypePos, imageCurr.length);
            
            if (imageCurr.indexOf('-full') == -1) {
                //passive image                
                if (imageCurr.indexOf(imgPassiveInit) == -1) {
                    imgPassive = imageCurr;
                    imgActive = imageCurr.substring(0, imageTypePos) + '-full' + imageType;
                    $.ajax({
                        url: imgActive,
                        async: false,
                        type: 'HEAD',
                        error: function () {
                            imgActive = imgActiveDefault;
                        }
                    });
                    imgPassiveInit = imgPassive;
                    imgActiveInit = imgActive;
                }                      
            }
            else {
                //active image
                if (imageCurr.indexOf(imgActiveInit) == -1) {
                    imgActive = imageCurr;
                    imgPassive = imageCurr.substring(0, imageTypePos - 5) + imageType;
                    $.ajax({
                        url: imgPassive,
                        async: false,
                        type: 'HEAD',
                        error: function () {
                            imgPassive = imgPassiveDefault;
                            
                        }
                    });
                    imgPassiveInit = imgPassive;
                    imgActiveInit = imgActive;
                }
            }            
        }

        //add onclick event to new image
        $('#nlDoc img').click(function () {        
            if ($(this).attr('link') != '') {
                window.open($(this).attr('link'), '_blank');
            }
        });

        //choose 'active' or 'passive' image depends on selected nl_group
        if ($("select[name*='group_']").attr('value') != 0 && $("select[name*='group_'] option:selected").attr('link') != '') {
            $('#nlDoc img').attr('src', imgActive);
        }
        else {
            $('#nlDoc img').attr('src', imgPassive);
        }
    }
}

function newsletterMainShopLocationSelect() {    
    if ($('#nlDoc').length > 0) {
        debugger;
        $("select[name*='group_']").change(function () {
            debugger;
                  initNewsletterImages();
                  var link = $("select[name*='group_'] option:selected").attr('link');      
                  if (link != '') {                      
                      $('#nlDoc img').attr({ src: imgActive, link: link }).css('cursor', 'pointer');                      
                  }
                  else {                      
                    $('#nlDoc img').attr({ src: imgPassive, link: link }).css('cursor', 'default');
                  }          
         }).change();         
    }
}

function newsletterTopShopLocationSelect(){
    $('.header_container select').change(function () {
          var groupId = $('.header_container select option:selected').attr('value');
          if(groupId != 0)
            window.location = 'newsletter_group_nl.html?nlGroupId=' + groupId;
     });    
}



function newsletterFrontDocumentsSelect(){
    var temp_select = $("select[name='nl-doc']").parent();
     $("select[name='nl-documents']").clone().appendTo(temp_select);
     $("select[name='nl-doc']").hide();
     $(".hidden").hide();
 }

 function openFile() {    
    var link = $("select[name='nl-documents']").find('option:selected').attr('link');
    if (link != '' && link != undefined)
         window.open($("select[name='nl-documents']").find('option:selected').attr('link'), '_blank');
}

function openDialog(params){
    params = params || {};	
	var dialog = window.showModalDialog('/dialogs/commonPopupWindow.html',
		params, 'center:yes; dialogHeight:550px;resizable:yes;dialogWidth:550px ')
	if(params.answer.resCode == 'OK')	{
		    return params.answer;
	}	
}


function slideshow(initImage, imgSetPos, picture_delay, opacity_delay){	   	  
    //var picture_delay = 2000; // in msec
    opacity_delay =  Math.floor(opacity_delay/10); // in msec 
    var min_opacity_step = 0;  
    var max_opacity_step = 50;    
    
    // pictures array
    var arr_div_pic = new Array();
    var arr_slides = document.getElementsByTagName('DIV');
	   var div_cnt = 0;
    for (var i = 0; i < arr_slides.length; i++){
 		     try{
 			        // take only div, which contain slideshow pictures
 			        if(arr_slides[i].getAttribute('type') == 'slideshow'+imgSetPos){ 		             
 		             arr_div_pic[div_cnt] = arr_slides[i].childNodes[0];
 				           div_cnt++;
 			        }
 		     }catch(e){}
    }
    
    // array of start image style
    var arr_startStyle = new Array();
    var count_pic = arr_div_pic.length;
    for (var i = 0; i < count_pic; i++){
    		for(var j = 0; j < arr_div_pic[i].childNodes.length; j++){
        if (arr_div_pic[i].childNodes[j].nodeType==1 && arr_div_pic[i].childNodes[j].nodeName.toUpperCase()=='IMG'){
            arr_div_pic[i]=arr_div_pic[i].childNodes[j];
                break;
            }
        }
			     arr_startStyle[i] = arr_div_pic[i].style.cssText;
    }
        
	   var cur_pic = 0;    
    function show_img(step, next_pic, initImage) {		              		      		      
		      try{            
            arr_startStyle[next_pic] = arr_startStyle[next_pic].replace(/none/,'block');
            var trans1 = parseFloat(step)/max_opacity_step;
            var trans2 = 1-(parseFloat(step)/max_opacity_step);
            
            var transPattern1 = "; filter:alpha(opacity="+Math.round(100*trans1)+");-moz-opacity:"+trans1+";opacity:"+trans1+";";
            var transPattern2 = "; filter:alpha(opacity="+Math.round(100*trans2)+");-moz-opacity:"+trans2+";opacity:"+trans2+";";
            
            arr_div_pic[cur_pic].style.cssText = arr_startStyle[cur_pic] + transPattern1;
            arr_div_pic[next_pic].style.cssText = arr_startStyle[next_pic] + transPattern2;
            
            if (step == max_opacity_step){
            //if (step == parseFloat((max_opacity_step - min_opacity_step)/2)){             
                $('.pf-navigator div').removeClass('selected');
                $('.pf-navigator div:eq('+next_pic+')').addClass('selected');
            }
            
            if(step > min_opacity_step){
 			            // while opacity is not 0
             	  step--;
 			  	         delay = opacity_delay;
			             }
			         else{ 			             			            
 			            // if opacity is 0 - change pictures pair
 				           arr_div_pic[cur_pic].style.cssText = arr_startStyle[cur_pic].replace(/block/,'none');
 				           arr_startStyle[cur_pic] = arr_startStyle[cur_pic].replace(/block/,'none');
 				           cur_pic = next_pic;
             	  if ((next_pic+1) < count_pic) next_pic++;
				            else next_pic = 0;
				            step = max_opacity_step;
 				           delay = picture_delay; 				            				           
            }            
            
            if (imgSetPos == 2 ) t2=setTimeout(function(){show_img(step, next_pic, initImage);}, delay);
            else setTimeout(function(){show_img(step, next_pic, initImage);}, delay);            
        }catch(e){}
    }
    if (imgSetPos == 2 ) t1 = setTimeout(function(){show_img(max_opacity_step, cur_pic+1, initImage);},picture_delay);
    else {
        $('.pf-navigator div').removeClass('selected');
        $('.pf-navigator div:first').addClass('selected');
        setTimeout(function(){show_img(max_opacity_step, cur_pic+1, initImage);},picture_delay);            
    }
}

function stopSlideshow(){
    clearTimeout(t1);
    clearTimeout(t2);
    timer_is_on=0;
}

function showImageWithPosition(pos){
    $('div[type = "slideshow2"]').css('display','none');
    $('div[type = "slideshow2"]:eq('+pos+')').css('display','block');
    $('div[type = "slideshow2"]:eq('+pos+') > a > img').css('display','block');
    $('div[type = "slideshow2"]:eq('+pos+') > a > img').css('opacity','1');
}

 function submitButton(){
    $('.form_submit').each(function(){
        if (!$(this).parent().hasClass('sb_outer2')){
            $(this).wrap('<div class="sb_outer0">');
            $(this).wrap('<div class="sb_outer1">');
            $(this).wrap('<div class="sb_outer2">');
        }
    });

    $('.submit').each(function(){
        if (!$(this).parent().hasClass('sb_outer2')){
            $(this).wrap('<div class="sb_outer0">');
            $(this).wrap('<div class="sb_outer1">');
            $(this).wrap('<div class="sb_outer2">');
        }
    });

    $('.test_form').each(function(){
        if (!$(this).parent().hasClass('sb_outer2')){
            $(this).wrap('<div class="sb_outer0">');
            $(this).wrap('<div class="sb_outer1">');
            $(this).wrap('<div class="sb_outer2">');
        }
    });
}
