$(document).ready(function(){
  
    MenuPadding('#top-menu');
   
    resizeCurrentBg();
    if($('#top-menu .current-menu-parent .sub-menu').length > 0){
        $('#top-menu-shadow ').css('top','17px');
    }

    if($('#alephbet .disabled-menu-item a').length > 0){
        $('#alephbet .disabled-menu-item a, a.disabled').click(function(e){
           e.preventDefault();
        });
    }

    if($('#album-picture-container').length > 0){
        
        $('#album-picture-container').cycle({
            pager:   '#gallery-pager',
            startingSlide: 2,
            delay: 5,
            containerResize: 0,
            width: 440,
            height: 330,
            fit: 1,
            backwards: true,
            pagerAnchorBuilder: function(idx, slide) {
                
                img=$(slide).find('img');
                return ('<li><a href="#"><img src="' + img[0].src + '" alt="" /></a></li>');
            }
        });
    }

    if($('#contact-form').length > 0)
        contactFormInit();

   if ($('#news-content').length >0 ){
      $('#news-content').vTicker({
           height: 70,
           showItems: 1,
           pause: 6500,
           animation: 'scroll',
           speed: 6000,
           mousePause: true
       }); 
       
       //setInterval('scrollNews()',2000);
      /* scrollNews();
       scrollNewsRun();*/
    }

    if($('#album-thumbs-list').length > 0){
        $('#scroll-up-album').click(function(){
            $('#album-thumbs-list').scrollList({
                direction: 'backward',
                layout: 'height'
            });
        });

        $('#scroll-down-album').click(function(){
            $('#album-thumbs-list').scrollList({
                direction: 'forward',
                layout: 'height'
            });
        });

        $('#filmstrip-right-nav').click(function(){
            $('#gallery-pager').scrollList({
                direction: 'backward',
                layout: 'width'
            });
        });

        $('#filmstrip-left-nav').click(function(){
            $('#gallery-pager').scrollList({
                direction: 'forward',
                layout: 'width'
            });
        });
    }

    if ($('#search-form').length > 0){
        $('#search-form input').initField();

        $('#search-form').submit(function(){
            var inputs = $(this).find('input');
            $(inputs).each(function(){
               if ($(this).data('defValue') == $(this).val()){
                   //$(this).val('');
                   $(this).attr('disabled','disabled');
                   $(this).css('background-color','#ffffff');
               }
            });

            return (true);
        });
    }
});


function resizeCurrentBg(){
    var li = $('#top-menu .sub-menu .current-menu-item,\n\
                 #top-menu .sub-menu .current-menu-parent,\n\
                 #top-menu .sub-menu .current-category-ancestor');
    var bg = li.find('img');
    var width = li.width();
    bg.width(width);
    bg.parent().show();
}

function contactFormInit(){

    //name field
    $('.form-text-field').click(function(e){
        if (typeof contactFormInit.defaults == 'undefined'){
            contactFormInit.defaults=new Object();
        }

        name = $(e.currentTarget).attr('name');
        val = $(e.currentTarget).val();
        if (typeof contactFormInit.defaults[name] == 'undefined'){
            contactFormInit.defaults[name] = val;
            $(e.currentTarget).blur(function(){
                if ($(e.currentTarget).val() == '')
                    $(e.currentTarget).val(contactFormInit.defaults[name]);
            });
        }
        
        if (val == contactFormInit.defaults[name]){
            $(e.currentTarget).val('');
        }
    });

    $('#contact-form').submit(function(e){


        e.preventDefault();
        valid = validate(this);

        if(valid){
            data = $(this).serialize();
            height = $('#main').css('height');
            $('#message-container').css('height',height);
            $('#wrapper').css('cursor','wait');
            $('#message-container, #message-wait').fadeIn();

            $('#close-contact-message').click(function(e){
                e.preventDefault();
                $('#message-container, #close-contact-message').fadeOut();
                $('#message').remove();
            });

            $.ajax({
                type: 'POST',
                data: data,
                success: function(msg){
                    message = $(msg).find('#message');
                    $('#message-wait').fadeOut(400,function(){
                        $('#close-contact-message').fadeIn();
                        $('#message-container').prepend(message);
                        $('#wrapper').css('cursor','default');
                        var f = document.getElementById('contact-form');
                        f.reset();
                    });

                }
            });
        }
    });

}

function validate(form){

    var valid=true;
    email = new RegExp('.*@.*.*');
    fields = {
        email: {name: form.email, exp: new RegExp('.*@.*.*')},
        //phone: {name: form.phone, exp: new RegExp('\\d{2,3}-\\d{7}')},
        phone: {name: form.phone, exp: new RegExp('(^\\d{2,3}-{0,1}\\d{7}$|טלפון)')},
        //topic: {name: form.topic, exp: new RegExp('[^(-1)]')},
        fullName: {name: form.fullName, exp: new RegExp('[^(שם)]')},
        //message: {name: form.message, exp: new RegExp('.{50}')}
    };
    for (key  in fields){
        field = fields[key];
        if (!(validate_field(field['name'],field['exp']))){
            valid = false;
        }
    }
    return (valid);
}


function validate_field(field,exp){
    var valid = true;
    val = $(field).attr('value');
    if (exp.exec(val) == null){
           valid = false;
           $(field).css('border','1px solid red');
    }else{
        $(field).css('border','1px solid black');
    }

    return (valid);
}

function MenuPadding(selector){
    var ulWidth = $(selector).width();
    var liList = $(selector + ' > li');
    var liWidth=0;

    for (curr=0; curr< liList.length; curr++){
        liWidth+=$(liList[curr]).width();
    }

    //calcucalting the absolute difference

    var diff=ulWidth-liWidth;
    var direction = diff/Math.abs(diff);
    var padding = direction*Math.floor(Math.abs(diff)/liList.length/2);

    var partPad = direction*Math.floor(Math.abs(diff)%(liList.length*2));
    /*if (padding == 0)
        padding=(diff/Math.abs(diff));*/

    for (curr = liList.length-1; curr>=0 && Math.abs(ulWidth-liWidth) !=0; curr-- ){
        $(liList[curr]).children('p').css('padding-right',function(){
            p = parseInt($(this).css('padding-right'));
            if (partPad != 0 ){
                p+=direction;
                partPad-=direction;
            }
            return (p+padding+'px');
        });
        $(liList[curr]).children('p').css('padding-left',function(){
            p = parseInt($(this).css('padding-left'));
            if (partPad != 0 ){
                p+=direction;
                partPad-=direction;
            }
            return (p+padding+'px');
        });

       liWidth+=2*padding;
   }
    
}


(function($){
    $.fn.scrollList = function(options){
        var defaults = {
            direction: 'forward',
            layout: 'width',
            duration: 'fast',
            steps: 1
        };
        if($(this).data("scroll_in_progress") == "1"){
            return false;
        }
        
        $(this).data("scroll_in_progress","1");
        var options = $.extend(defaults, options);

        var first = $(this).children('li').first();
        var last =  $(this).children('li').last();
        var next = first.next();

        var step=1;
        if (options.direction == 'backward'){
            step=step*(-1);
        }
        var property;
        var animateOptions;
        if (options.layout == 'height'){
            step = step * (next.position().top - first.position().top);
            property = 'top';
            animateOptions = {top: '+='+step+'px'};
        }

        if (options.layout == 'width'){
            step = step * (next.position().left - first.position().left);
            property = 'left';
            animateOptions = {left: '+='+step+'px'};
        }


        

        $(this).css('position','relative');
        
        if (options.direction == 'backward'){
            $(this).append(first.clone(true));
        }
        if (options.direction == 'forward'){
            $(this).prepend(last.clone(true));
            $(this).css(property,step*(-1) + 'px');
        }


        //animateOptions.duration = options.duration;
        $(this).animate(animateOptions,options.duration,function(){
            if (options.direction == 'backward'){
                $(this).children('li').first().remove();
            }
             if (options.direction == 'forward'){
                 $(this).children('li').last().remove();
             }
            $(this).css(property,'0');
            $(this).data("scroll_in_progress","0");
        })
    };
})(jQuery);


(function($){
    $.fn.initField = function(){

        $(this).each(function(){
            $(this).data({defValue: $(this).val()});
            var name = $(this).attr('name');
            var urlVar = $.getUrlVar(name);
            if (typeof (urlVar) != "undefined"){
                var val=decodeURIComponent(urlVar);
                $(this).val(val.replace("+"," "));
            }
        });
        
        $(this).blur(function(){
            if ($(this).val() == '')
                $(this).val($(this).data('defValue'));
        });

        $(this).click(function(){
            if ($(this).val() == $(this).data('defValue')){
                $(this).val('');
            }
        });
        
    };
})(jQuery);

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});


function scrollNews(){
  $('#news-list').animate({top: "-=1px"},100,scrollNews);
}

function scrollNewsRun(){
    var n = $('#news-list').queue("fx");
    //var first = $('#news-list').first("li");
    setTimeOut(scrollNewsRun,100);
}
