$(document).ready(function() {
    
    /**
     * Active Menu Item
     */
    $('#nav').activeMenu({ 
        idSwitch: 'active',  // id used for active state 
        defaultSite: 'idunketchup.no',  // site URL 
        defaultIndex: 1  // active item used for default site URL 
    }); 
    
    /**
     * jQuery Scrollpane for PageRect
     */
    //$('.pagerect').jScrollPane();
    $('#scrollbar1').tinyscrollbar({ sizethumb: 35 });
    
    /**
     * Register AJAX Form
     */
     var ranid = Math.random();
     var access    = "";
    
     $("form#submit").submit(function() {
     	
        $.ajax({
                type:   "POST",
                url:    "wp-content/themes/idunketchup/access.php",
                data:   "id="+ranid,
                success: function( data ){
                    if( data.length > 1 )
                    {
                        access = data;
                        checkCodes();
                    }
                }
        });
        
    	return false;  
    });
    
    function checkCodes()
    {
    	var code1     = $('#code1').attr('value') +":"+$('#code11').attr('value');  
        var code2     = $('#code2').attr('value') +":"+$('#code22').attr('value');   
        var code3     = $('#code3').attr('value') +":"+$('#code33').attr('value'); 
        
        $.ajax({  
            type: "POST",  
            url: "wp-content/themes/idunketchup/process.php",  
            data: "code1="+ code1 +"&code2="+ code2 +"&code3=" + code3,  
            success: function( data, textStatus ){ 
                if( data == "1" )
                {
                    $('#rightControl').trigger('click');
                    $('div.success').hide();
                    $('div.success').html( '' );
                    $('a#kodelink').attr('href', 'http://www.ellos.no/?ref=idunketchup&basketoffer=0325');
                }
                else
                {
                    $('div.success').html( data );
                    $('div.success').fadeIn();
                    $('div#helpbox').fadeIn();
                }
            }  
        });
        
        return false;
    }
    
    $('a#closehelp').click(function(){
         $('div#helpbox').hide();
         return false;
    });
    
    /**
     * Email Form
     */
    
    var userEmail = "";
    $('#submit-mail').click(function() {  
        var email     = $('#email').attr('value');
        var age       = $('#age').attr('checked');
        var villkor   = $('#villkor').attr('checked');
        var info      = $('#info').attr('checked');
        
        registerUser( email, age, villkor, info );
        
        /*
        $.ajax({
                type:   "POST",
                url:    "wp-content/themes/idunketchup/access.php",
                data:   "id="+ranid,
                success: function( data ){
                    if( data.length > 1 )
                    {
                        access = data;
                        registerUser( email, age, villkor, info );
                    }
                }
        });
        */
          
        return false;  
    });
    
    function registerUser( email, age, villkor, info )
    {
        if( !isValidEmailAddress( email ) )
        {
            $('div.successmail').html( 'Ugyldig e-post' );
            $('div.successmail').fadeIn();
        }
        else
        {
            $('div.successmail').hide();
        }
        if( isValidEmailAddress( email ) && age && villkor )
        {
            userEmail = email;
            $.ajax({  
                type: "POST",  
                url: "wp-content/themes/idunketchup/registration.php",  
                data: "email="+ email+"&age="+age+"&villkor="+villkor+"&info="+info,  
                success: function( data, textStatus ){ 
                    if( data == "1" )
                    {
                        $('#rightControl').trigger('click');
                    }
                    else
                    {
                        $('div.successmail').html( data );
                        $('div.successmail').fadeIn();
                    }
                }  
            });
        }
        
        return false;
    }
     
    function isValidEmailAddress(emailAddress) {
        var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
        return pattern.test(emailAddress);
    };
    
    /**
     * Fade in PageContent
     */
    $('#pagecontent').hide();
    $('#pagecontent').fadeIn();
    
    
    /* 
     * Cross-browser event handling, by Scott Andrew
     */
    function addEvent(element, eventType, lamdaFunction, useCapture) {
        if (element.addEventListener) {
            element.addEventListener(eventType, lamdaFunction, useCapture);
            return true;
        } else if (element.attachEvent) {
            var r = element.attachEvent('on' + eventType, lamdaFunction);
            return r;
        } else {
            return false;
        }
    }
    
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && ( theInput.className.match(/\binnorm\b/) || theInput.className.match(/\binmail\b/) ) ) {  
            /* Add event handlers */          
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
            
            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
    
    /**
     * Form default text
     */
    function clearDefaultText(e) {
        var target = window.event ? window.event.srcElement : e ? e.target : null;
        if (!target) return;
        
        if (target.value == target.defaultText) {
            target.value = '';
        }
    }
    
    function replaceDefaultText(e) {
        var target = window.event ? window.event.srcElement : e ? e.target : null;
        if (!target) return;
        
        if (target.value == '' && target.defaultText) {
            target.value = target.defaultText;
        }
    }
    
    /**
     * Products
     */
    var prodcontent = $('.leftprods').html();
    
    $('ul#prods li a').each(function(){
        $(this).click(function(){
            $('.scrollbar').hide();
            var id = $(this).attr('id');
            var refs = $('#refs ul li');
            $(refs).each(function(){
               if( $(this).hasClass(id) )
               {
                   var copy = $(this);
                   if( $('.leftprods li') )
                   $('#refs ul').append( $('.leftprods li') );
                   
                   $('.leftprods').html(copy);
                   
                   $('#closeprod').show();
               }
            });
            
            return false;
        }); 
    });
    
    $('#closeprod').click(function(){
        $('.scrollbar').show();
        $('.leftprods').html(prodcontent);
        $(this).hide();
        return false;
    });
    
     $(".prodlink").click(function(){
        var id = $(this).attr('id');
        var refs = $('#refs ul li');
        $(refs).each(function(){
           if( $(this).hasClass(id) )
           {
               $('.leftprods').html($(this));
           }
        });
        
        return false;
    });
    /*
    $("#youtube-player-container").tubeplayer({
        width: 360, // the width of the player
        height: 269, // the height of the player
        allowFullScreen: "true", // true by default, allow user to go full screen
        initialVideo: "hnC_i74G0FE", // the video that is loaded into the player
        playerID: "youtube-player", // the ID of the embedded youtube player
        preferredQuality: "default",// preferred quality: default, small, medium, large, hd720
        onPlay: function(id){}, // after the play method is called
        onPause: function(){}, // after the pause method is called
        onStop: function(){}, // after the player is stopped
        onSeek: function(time){}, // after the video has been seeked to a defined point
        onMute: function(){}, // after the player is muted
        onUnMute: function(){} // after the player is unmuted
    });
    */
    $('#vid1').click(function(){
        setMovie("wp-content/themes/idunketchup/video/tomater.flv");
        return false;
    });
    
    $('#vid2').click(function(){
        setMovie("wp-content/themes/idunketchup/video/20.flv");
        return false;
    });
    
    $('#vid3').click(function(){
        setMovie("wp-content/themes/idunketchup/video/20_pack.flv");
        return false;
    });
    
    /**
     * Later shopping
     */
    $('a#later').click(function(){
        
        $.ajax({
            type:"POST",
            url:"wp-content/themes/idunketchup/mail.php",
            data:"email=" + userEmail,
            success: function( data, textStatus ) {
                
                $('div#latewrap').html("<h5>Gavekort sendt</h5>");
                $('div#kodelinkwrap').hide();
            }
        })
        
        return false;
    });
    
    if( $("#jwflic").length )
    {
    	jwplayer("jwflic").setup({
		autostart: true, file: "wp-content/themes/idunketchup/video/tomater.flv", duration: 57, flashplayer: "wp-content/themes/idunketchup/video/player.swf", volume: 90, width: 360, height:204, skin: "wp-content/themes/idunketchup/video/glow.zip", stretching: "fill"
		});
    }
    
	
	function setMovie( filePath )
	{
		jwplayer("jwflic").remove();
		
		jwplayer("jwflic").setup({
autostart: true, file: filePath, duration: 57, flashplayer: "wp-content/themes/idunketchup/video/player.swf", volume: 90, width: 360, height:204, skin: "wp-content/themes/idunketchup/video/glow.zip", stretching: "fill"
});
	}
    
});

