/*
 *  coded by zack @ [ mog.(labs), berlin: http://m-og.eu/ ]
 *  
 */

var menua50 = new Image(1,50);
menua50.src = '/media/xl/css/img/a50-bg.png';

$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};


// IE6 detection
ie6User = {status:'false'};
var is_ie6 = (window.external && typeof window.XMLHttpRequest == "undefined");
if (is_ie6) {ie6User.status ='true';}
else {ie6User.status ='false';}

// jCarousel + galleria integration
var jC = null;
function jcInit(carousel) {
    jC = carousel;
}
function jcScroll(carousel) {
    // scroll to galleria '.active' item
    var selected = $("#gallery").find("li.active").attr('jcarouselindex');
    carousel.scroll($.jcarousel.intval(selected));
    return false;
}

// jwplayer
function loadPlayer(file,image,duration,skin){
	var so = new SWFObject('/media/xl/jwplayer/player-licensed.swf','mobject','615','370','9.0.115');
	so.addParam('allowfullscreen','true');
	so.addParam('allowscriptaccess','always');
    so.addParam('allownetworking','all');
	so.addParam('wmode','transparent');
    if (image){so.addVariable('image',image);}
	so.addVariable('autostart','false');
	so.addVariable('stretching','fill');
	so.addVariable('controlbar','bottom');
	so.addVariable('file',file);
	if (duration && duration !== '0'){so.addVariable('duration', duration);}
    so.addVariable("skin","/media/xl/jwplayer/skins/"+skin+"/stylish_slim.swf");
	so.write('jw_player');
}

function initializeMap(md) {
	// contact widget map
    
	if (GBrowserIsCompatible()) {

		var map = new GMap2($("#mapBox").get(0));

	    // GMapUIOptions class
		// ref: http://code.google.com/apis/maps/documentation/reference.html#GMapUIOptions
        var uiOptions = map.getDefaultUI();
        /*
        uiOptions.maptypes.normal = true;
        uiOptions.maptypes.satelite = false;
        uiOptions.maptypes.hybrid = false;
        uiOptions.maptypes.physical = false;
        */
        if (md.scroll_zoom=='0') {
            uiOptions.zoom.scrollwheel = false;
        } else {
            uiOptions.zoom.scrollwheel = true;
        }
		if (md.largemapcontrol3d=='0') {
            uiOptions.controls.largemapcontrol3d = false;
        } else {
            uiOptions.controls.largemapcontrol3d = true;
        }
		if (md.smallzoomcontrol3d=='0') {
            uiOptions.controls.smallzoomcontrol3d = false;
        } else {
            uiOptions.controls.smallzoomcontrol3d = true;
        }
		if (md.scalecontrol=='0') {
            uiOptions.controls.scalecontrol = false;
        } else {
            uiOptions.controls.scalecontrol = true;
        }
		if (md.maptypecontrol=='0') {
            uiOptions.controls.maptypecontrol = false;
        } else {
            uiOptions.controls.menumaptypecontrol = false;
            uiOptions.controls.maptypecontrol = true;
        }
		if (md.menumaptypecontrol=='0') {
            uiOptions.controls.menumaptypecontrol = false;
        } else {
            uiOptions.controls.maptypecontrol = false;
            uiOptions.controls.menumaptypecontrol = true;
        }
	    map.setUI(uiOptions);

		// disable map dragging
	    if (md.disablemapdrag=='1') {map.disableDragging();}

		var screenPos = new GLatLng(md.lat, md.lng);
	    map.setCenter(screenPos, parseInt(md.zoom));

		var screenIcon = new GIcon(G_DEFAULT_ICON);
        
	    // create point from input object
		var point = new GLatLng(md.lat, md.lng);

	  	markerOptions = {icon:screenIcon};
	    var marker = new GMarker(point, markerOptions);
        
        var markerHtml = "<span class='mapInfo'>";
                markerHtml += "<span class='map_text'>";
                    markerHtml += "<span class='map_title'>"+md.title+"</span><br />";
                    markerHtml += ""+md.address1+"<br />";
                    markerHtml += ""+md.address2+" "+md.address3+"<br />";
                    if (md.tel) {markerHtml += ""+md.tel+"<br />";}
                    if (md.url) {markerHtml += "<span class='map_url'><a href='"+md.url+"'>"+md.url+"</a></span>";}
                markerHtml += "</span>";
                markerHtml += "<img class='map_thumb' src='"+md.thumb+"' alt='' />";
            markerHtml += "</span>";

        if (ie6User.status == 'true'){
            GEvent.addListener(marker, "click", function() {
                window.open("http://maps.google.co.uk/maps?f=q&source=s_q&hl="+md.language+"&geocode=&q=LED+XL+BV,+rotterdam&sll=62.066992,-54.381392&sspn=174.12872,360&ie=UTF8&hq=LED+XL+BV,&hnear=Rotterdam,+The+Netherlands&ll=51.983189,4.709015&spn=0.608978,1.476288&z=10&iwloc=A&iwstate1=dir");
            });
        }
        else {
            marker.openInfoWindowHtml(markerHtml);
            GEvent.addListener(marker, "click", function() {
                marker.openInfoWindowHtml(markerHtml);
            });
        }


		// create and pan to new off-center point
		var p = marker.getLatLng();
		var x = p.lat()-0.0;
		var y = p.lng()+0.00105;
		var pnew = new GLatLng(x,y);
	    map.panTo(pnew);
        
	    map.addOverlay(marker);
        
	}
}

$(document).ready(function(){

	// x-browser hover function for main menu
    $("#menu li.bx").hover(function(){$(this).addClass("hover");},function(){$(this).removeClass("hover");});

    // search
    $("#searchBtn").bind("click",function(e){
        e.preventDefault();
        var q = $("#xl_search").attr('value');
        if (q !=='search' && q !== ''){$("#searchForm").submit();}
    });
    
    $("#xl_search").focus(function(){
            $("#xl_search").css({'background':'#fff'}).attr('value','');
            $("#searchBtn").css({'background':'#fff'});
        }).blur(function(){
            $("#xl_search").css({'background':'#999'});
            $("#searchBtn").css({'background':'#999'});
        });

    // language selector
    $("#langDrop").hide();
    var state = false;
    $("#langButton").click(function(){
        if (!state){
           state = true;
           $("#langDrop").css({'display':'block'});
           $(this).animate({'height':'88px'},170, function(){
               //$("#langDrop").fadeIn(100);
           });
        }
        else if (state){
           state = false;
           $(this).animate({'height':'25px'},50, function(){
                $("#langDrop").css({'display':'none'});
           });
        }
    });

    /*
    $("div#lbTitle").toggle(
        function(){
           $("#langDrop").css({'display':'block'});
           $(this).animate({'height':'88px'},150, function(){});
        },
        function(){
                $("#langDrop").css({'display':'none'});
           $(this).animate({'height':'25px'},50, function(){
           });
        });
    */


    $("#langButton").hover(
        function(){
            //
        },function(){
            $("#langDrop",this).fadeOut(400);
            $(this).animate({'height':'25px'},400);
    });

    // opacity hover states for blocks ---------------------
    // ..hoverIntent plugin: http://cherne.net/brian/resources/jquery.hoverIntent.html
    var hiconfig = {
        sensitivity: 7, // number = sensitivity threshold (must be 1 or higher)
        interval: 50, // number = milliseconds for onMouseOver polling interval
        over: function(){
            $(this).css({'cursor':'pointer'}).fadeTo(300, 1);
        },
        timeout: 200, // number = milliseconds delay before onMouseOut
        out: function(){
            $(this).fadeTo(300, 0.6);
        }
    };
    $(".smObj, .smObj-r, .bigObj, .bigObj-r, .res_a, .res_b, .sm-content").fadeTo(10, 0.7); // set inital state
    $(".smObj, .smObj-r, .bigObj, .bigObj-r, .res_a, .res_b, .sm-content").hoverIntent(hiconfig);

    /*
    $(".smObj, .smObj-r, .bigObj, .bigObj-r, .res_a, .res_b, .sm-content").fadeTo(10, 0.7); // set inital state
    $(".smObj, .smObj-r, .bigObj, .bigObj-r, .res_a, .res_b, .sm-content").hover(
        function(){
            $(this).css({'cursor':'pointer'}).fadeTo(300, 1);
        },
        function(){
            $(this).fadeTo(500, 0.6);
        }
    );
    */
    $(".smObj, .smObj-r, .bigObj, .bigObj-r").live("click", function(e){
        var href=$("a.blockheader",this).attr("href");
        if (href!==undefined){window.location = href;} else {e.preventDefault();}
    });
    $(".res_a, .res_b").live("click", function(e){ // search results
        var href=$("a.resLink",this).attr("href");
        if (href!==undefined){window.location = href;} else {e.preventDefault();}
    });
    $("#hcard").live("click", function(e){ // HCARDS (contact people)
        var href=$("a.cat-link",this).attr("href");
        if (href!==undefined){window.location = href;} else {e.preventDefault();}
    });
    $(".smcHover").live("click", function(e){ // spotlight + latest articles
        var href=$("a.smcLink",this).attr("href");
        if (href!==undefined){window.location = href;} else {e.preventDefault();}
    });
    //  map ------------------------------------------------

    if ($("#mapBox").length){
        var md = $("#mapBoxData").serializeObject();
        initializeMap(md);
    }
    
    // jwplayer --------------------------------------------
    if ($("#playerData").length){
        var file = $("#playerData .pd_mov").attr('content');
        var image = $("#playerData .pd_image").attr('content');
        var duration = $("#playerData .pd_duration").attr('content');
        var skin = $("#playerData .pd_skin").attr('content');
        loadPlayer(file,image,duration,skin);
    }
    // -----------------------------------------------------
    //
    // modules table: help text ----------------------------
    $("a.mt_help, a.ctitle").live("click",function(e){
        e.preventDefault();
        var h = $(this).attr("title");
        $("#mt_info").css({'display':'block'})
                     .animate({'height':'25px'},100, function(){
                         $(this).html("<p>"+h+"</p>");
                     });
    });
    $("#mt_info").live("click",function(){
        $(this).empty()
               .animate({'height':'0px'},100, function(){
                 $(this).css({'display':'none'});
               });
    });
    // -----------------------------------------------------
    

    if($("#gallery").length) { //if #gallery is in the DOM
        // attach jCarousel
        $('ul#gallery').jcarousel({
            scroll: 3,
            visible: 5,
            animation: 100,
            initCallback: jcInit
        });
        // attach Galleria
        $('ul#gallery').galleria({
			history   : false, // activates the history object for bookmarking, back-button etc.
			clickNext : true, // helper for making the image clickable
			insert    : '#galleriaContentBox', // the containing selector for our main image
			onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes

                // fetch the thumbnail container
                var _li = thumb.parents('li');

                // count items
                var n = parseInt(_li.siblings().length);

                if (typeof n == 'undefined' || n == 0) {
                    // disable click behaviour
                    $.galleria.clickNext = false;
                }
                else if (typeof n == 'number' && n != 0){
                    // enable click behaviour
                    $.galleria.clickNext = true;
                    
                    // fade in the image & caption
                    if(! ($.browser.mozilla && navigator.appVersion.indexOf("Win")!=-1) ) { // FF/Win fades large images terribly slow
                        image.css('display','none').fadeIn(500);
                    }

                    // fade out inactive thumbnail
                    _li.siblings().children('img.selected').fadeTo(300,0.3);

                    // fade in active thumbnail
                    thumb.fadeTo('fast',1).addClass('selected');

                    // this will add a class to landscape images allowing extra margin
                    if (image.height() < image.width()) {
                        $('#galleriaContentBox').addClass('landscape');
                    } else {
                        $('#galleriaContentBox').removeClass('landscape');
                    }
                }
                // scroll jcarousel to active item
                jcScroll(jC);
			},
			onThumb : function(thumb) { // thumbnail effects goes here
                
				// fetch the thumbnail container
				var _li = thumb.parents('li');

				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.3';

				// fade in the thumbnail when finnished loading
				thumb.css({display:'none',opacity:_fadeTo}).fadeIn(500);

				// hover effects
				thumb.hover(
					function() {thumb.fadeTo('fast',1);},
					function() {_li.not('.active').children('img').fadeTo('fast',0.3);} // don't fade out if the parent is active
				)
			}
		});
        var zItemIndex = 0; // INTEGER : item number (zero indexed)
        var firstItem = $('#gallery li:eq('+zItemIndex+')').addClass('active').find('img').addClass('selected');
        $.galleria.activate(firstItem.attr('src'));
    }

    /* form validation 
     * ------------------------------------------------------- */
    // form validation
	function validEmail(str){
		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(str);
	}
/*
	function validPhone(str){
		str = str.replace(/\s+/g, '');
		var pattern = new RegExp(/^\d+$/);
		return pattern.test(str);
	}
*/
	function validPhone(str){
		// remove space, . and - chars
		str	= str.replace(/[\s\.-]+/g, '');
		// match any amount of digits with or without a + in front of them
		var pattern	= new RegExp(/^\+?\d+$/);
		return pattern.test(str);
	}

	function validName(str){
		str = str.replace(/\s+/g, '');
		var pattern = new RegExp(/^[a-zA-Z]+$/);
		return pattern.test(str);
	}

	$("#verstuur").click(function(e){
		e.preventDefault();
		var lang = $("#cform #lang").attr('value');
        //
		var name = $("#cform #naam").attr('value');
		var email = $("#cform #email").attr('value');
		var tel = $("#cform #telefoon").attr('value');
		$("#email, #naam, #telefoon").css({'background':'#282828'});

		if (!email || !name || !tel) {
			if (!email){$("#email").css({'background':'#ad0000'});}
			if (!name){$("#naam").css({'background':'#ad0000'});}
			if (!tel){$("#telefoon").css({'background':'#ad0000'});}
		}
		else {
			// validate
			var valid = new Array();
            //
			if (email !== ''){
				if (validEmail(email)) {valid[email] = true;}
				else {valid[email] = false;}
			}
			else {valid[email] = true;}
            //
	/*
	 not really needed..
			if (name !== ''){
				if (validName(name)) {valid[name] = true;}
				else {valid[name] = false;}
			}
			else {valid[name] = true;}
	*/
			{valid[name] = true;}
            //
			if (tel !== ''){
				if (validPhone(tel)) {valid[tel] = true;}
				else {valid[tel] = false;}
			}
			else {valid[tel] = true;}
            
			// submit or display errors
			if (valid[email] == true && valid[name] == true && valid[tel] == true){

                var str = $("#cform").serialize();
                $("#cform").clearForm();

				$("h1.s40white,#cformWrapper").empty();
				$("#cformWrapper").append("<div id='cformResults'><img src='/media/xl/graphics/loading.gif' alt='loading' /></div>");

				// ajax post to server
				$.ajax({
					type: "POST",
					url: "/contact/load/"+lang+"/",
					//url: "/contact/load/en/",
					data: str,
                    dataType: "json",
					success: function(data){
						$("#cformResults").html(data.response);
					}
				});
			}
			else {
				if (!valid[email]){
					$("#email").css({'background':'#ad0000'});
				}
				if (!valid[name]){
					$("#naam").css({'background':'#ad0000'});
				}
				if (!valid[tel]){
					$("#telefoon").css({'background':'#ad0000'});
				}
			}
		}

	});

});

/* SIFR config */
/*
var prioriSan_regular = {src: '/media/xl/flash/font_PrioriSan.swf'};
var prioriSan_regularAlt = {src: '/media/xl/flash/font_PrioriSan_alt.swf'};

// See also <http://wiki.novemberborn.net/sifr3/JavaScript+Configuration>.
// read <http://wiki.novemberborn.net/sifr3/DetectingCSSLoad>.
// sIFR.useStyleCheck = true;
sIFR.activate(prioriSan_regular, prioriSan_regularAlt);

//    var futura = { src: '/path/to/futura.swf' };
//    var garamond = { src '/path/to/garamond.swf' };
//    var rockwell = { src: '/path/to/rockwell.swf' };
//
//    sIFR.activate(futura, garamond, rockwell);
// <http://wiki.novemberborn.net/sifr3/JavaScript+Methods>
// Read more about styling at <http://wiki.novemberborn.net/sifr3/Styling>.

sIFR.replace(prioriSan_regular, {
  selector: 'h1.grey',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #999999; }']
});

// H1 color set
sIFR.replace(prioriSan_regularAlt, {
  selector: 'h1.s40grey',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #999999; font-weight: normal;}',]
});
sIFR.replace(prioriSan_regularAlt, {
  selector: 'h1.s40yellow',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #ffff00; font-weight: normal;}',
    ]
});
sIFR.replace(prioriSan_regularAlt, {
  selector: 'h1.s40blue',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #0099cc; font-weight: normal;}',]
});
sIFR.replace(prioriSan_regularAlt, {
  selector: 'h1.s40green',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #99cc00; font-weight: normal;}',]
});
sIFR.replace(prioriSan_regularAlt, {
  selector: 'h1.s40white',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #ffffff; font-weight: normal;}',]
});

// H2 color set
sIFR.replace(prioriSan_regular, {
  selector: 'h2.grey',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #999999; }']
});
sIFR.replace(prioriSan_regular, {
  selector: 'h2.yellow',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #ffff00; }']
});
sIFR.replace(prioriSan_regular, {
  selector: 'h2.blue',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #0099cc; }']
});
sIFR.replace(prioriSan_regular, {
  selector: 'h2.green',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #99cc00; }']
});
sIFR.replace(prioriSan_regular, {
  selector: 'h2.white',
  wmode: 'transparent',
  css: ['.sIFR-root { color: #ffffff; }']
});*/   
/* end SIFR config */

