/**
 * @author Simon Zeeck
 */
var debug = false;
var $j = jQuery.noConflict();

(function($) {		
	//Events
	$(function() {
		if (debug) console.log("jQuery - Start document redy");
	
		// mousedown on menu item
		$("#mainmenu li a").mousedown(function(){
			$(this).parent().addClass('mousedown');
			if (debug) console.log("Mouse down");
		});

		// bind mouseup activities
		$(document).bind('mouseup', function(e) {
			// remove mousedown class
			$("#mainmenu li").removeClass('mousedown');
		}); // end bind mouseup

		
		/*Modal Window 		
		$('.input-text').click(function() { 
		    alert('h');
			//if ($(this).val() == 'Enter search term') {   
		    //    $(this).data('original', $(this).val()).val('');
		    //}
		});

		$('#searchform').blur(function() { 
		    if ($(this).val() == '') {   
		        $(this).val($(this).data('original'));
		    }
		});*/

		var contact = {
				message: null,
				init: function () {
					//$('#contact-form input.contact, #contact-form a.contact').click(function (e) {
						$(".bind_contact").click(function (e) {
						e.preventDefault();

						// load the contact form using ajax
						$.get("/wp-content/themes/vt/contact.php", function(data){
							// create a modal dialog with the data
							$(data).modal({
								closeHTML: "<a href='#' title='Close' class='modal-close'>Stäng</a>",
								position: ["5%",],
								overlayId: 'contact-overlay',
								containerId: 'contact-container',
								onOpen: contact.open,
								onShow: contact.show,
								onClose: contact.close
							});
						});
					});
				},
				open: function (dialog) {
					// add padding to the buttons in firefox/mozilla
					if ($.browser.mozilla) {
						$('#contact-container .contact-button').css({
							'padding-bottom': '2px'
						});
					}
					// input field font size
					if ($.browser.safari) {
						$('#contact-container .contact-input').css({
							'font-size': '.9em'
						});
					}
					$('#contact-container').css({
						'position':'absolute'
						
					});
					$.scrollTo(0);
					
					//Handle textfield
					$('#contact-container .input-text').click(function() { 
						if (( $(this).val() == 'Fyll i ditt namn' || 
							  $(this).val() == 'Fyll i din e-post' ||
							  $(this).val() == 'Fyll i ditt telefonnummer') ){
									$(this).data('original', $(this).val()).val('');
								}
					});
					
					$('#contact-container .input-text').blur(function() { 
					    if ($(this).val() == '') {   
					        $(this).val($(this).data('original'));
					    }
					});
					
					// dynamically determine height
					var h = 460;
					if ($('#contact-subject').length) {
						h += 26;
					}
					if ($('#contact-cc').length) {
						h += 22;
					}

					var title = $('#contact-container .contact-title').html();
					$('#contact-container .contact-title').html('Loading...');
					dialog.overlay.fadeIn(200, function () {
						dialog.container.fadeIn(200, function () {
							dialog.data.fadeIn(200, function () {
								$('#contact-container .contact-content').animate({
									height: h
								}, function () {
									$('#contact-container .contact-title').html(title);
									$('#contact-container form').fadeIn(200, function () {
										$('#contact-container #contact-name').focus();

										$('#contact-container .contact-cc').click(function () {
											var cc = $('#contact-container #contact-cc');
											cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
										});

										// fix png's for IE 6
										if ($.browser.msie && $.browser.version < 7) {
											$('#contact-container .contact-button').each(function () {
												if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
													var src = RegExp.$1;
													$(this).css({
														backgroundImage: 'none',
														filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
													});
												}
											});
										}
									});
								});
							});
						});
					});
				},
				show: function (dialog) {
					$('#contact-container .contact-send').click(function (e) {
						e.preventDefault();
						// validate form
						if (contact.validate()) {
							var msg = $('#contact-container .contact-message');
							msg.fadeOut(function () {
								msg.removeClass('contact-error').empty();
							});
							$('#contact-container .contact-title').html('Sending...');
							$('#contact-container form').fadeOut(200);
							$('#contact-container .contact-content').animate({
								height: '140px'
							}, function () {
								$('#contact-container .contact-loading').fadeIn(200, function () {
									$.ajax({
										url: '/wp-content/themes/vt/contact.php',
										data: $('#contact-container form').serialize() + '&action=send',
										type: 'post',
										cache: false,
										dataType: 'html',
										success: function (data) {
											// I want to ask user 
											$('#contact-container .contact-loading').fadeOut(200, function () {
												$('#contact-container .contact-title').html('Thank you!');
												msg.html(data).fadeIn(200);
											});
											
											//Would be nice to close window here
											this.close;
										},
										error: contact.error
									});
								});
							});
						}
						else {
							//Not valid input
							if ($('#contact-container .contact-message:visible').length > 0) {
								var msg = $('#contact-container .contact-message div');
								msg.fadeOut(200, function () {
									msg.empty();
									contact.showError();
									msg.fadeIn(200);
								});
							}
							else {
								//$('#contact-container .contact-message').animate({
								//	height: '30px'
								//}, contact.showError);
							}
							
						}
					});
				},
				close: function (dialog) {
					$('#contact-container .contact-message').fadeOut();
					$('#contact-container .contact-title').html('Goodbye...');
					$('#contact-container form').fadeOut(200);
					$('#contact-container .contact-content').animate({
						height: 40
					}, function () {
						dialog.data.fadeOut(200, function () {
							dialog.container.fadeOut(200, function () {
								dialog.overlay.fadeOut(200, function () {
									$.modal.close();
								});
							});
						});
					});
				},
				error: function (xhr) {
					alert(xhr.statusText);
				},
				validate: function () {
					contact.message = '';
					var isValid = true;
					if (!$('#contact-container #forminput-sendername').val()) {
						//contact.message += 'Name is required. ';
						//Add Error here
						//#contact-name
						$('#forminput-sendername_error').append("fel");
						isValid = false;
					}

					var email = $('#contact-container #forminput-senderemail').val();
					if (!email) {
						//contact-email
						//contact.message += 'Email is required. ';
						$('#forminput-senderemail_error').append("fel");
						isValid = false;
					}
					else {
						if (!contact.validateEmail(email)) {
							//contact.message += 'Email is invalid. ';
							//contact-email
							//contact.message += 'Email is required. ';
							$('#forminput-senderemail_error').append("fel");
							isValid = false;
						}
					}

					//Add some code for e-mail or phone here
					
					//if (!$('#contact-container #contact-message').val()) {
					//	contact.message += 'Message is required.';
					//}

					//if (contact.message.length > 0) {
					//	return false;
					//}
					//else {
					//	return true;
					//}
					
					return isValid;
				},
				validateEmail: function (email) {
					var at = email.lastIndexOf("@");

					// Make sure the at (@) sybmol exists and  
					// it is not the first or last character
					if (at < 1 || (at + 1) === email.length)
						return false;

					// Make sure there aren't multiple periods together
					if (/(\.{2,})/.test(email))
						return false;

					// Break up the local and domain portions
					var local = email.substring(0, at);
					var domain = email.substring(at + 1);

					// Check lengths
					if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
						return false;

					// Make sure local and domain don't start with or end with a period
					if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
						return false;

					// Check for quoted-string addresses
					// Since almost anything is allowed in a quoted-string address,
					// we're just going to let them go through
					if (!/^"(.+)"$/.test(local)) {
						// It's a dot-string address...check for valid characters
						if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
							return false;
					}

					// Make sure domain contains only valid characters and at least one period
					if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
						return false;	

					if (debug) console.log("valid");
					return true;
				},
				showError: function () {
					$('#contact-container .contact-message')
						.html($('<div class="contact-error"></div>').append(contact.message))
						.fadeIn(200);
				}
			};
			contact.init();
			//*End Contact form (Move outside document redy?)
			
			//Some Facebook functions
			//http://www.facebook.com/#!/group.php?gid=18132872668	 //Dynamic Group id
		
			var facebook = {
		        feedURL: 'https://graph.facebook.com/18132872668/feed/?access_token=117250341658871|exA2GNAAgswtBPXFr98sPbkD8H4&limit=10&',
		        getFeed: function() {
		          var self = this;
		          var limit = 10;
		          $.getJSON(this.feedURL + 'callback=?', function(feed) {
		            var counter = 0;
		            $.each(feed.data, function(index, item) {
		              if(counter == limit) return;              
		              self.renderHTML(item);
		              counter++;
		            });
		            self.animate(limit);
		          });
		        },
		        animate: function(limit) {
		          var counter = 0;
		          var self = this;
		          var timer = 5000;
		          setInterval(function() {
		            self.animateItem(counter);
		            counter++;
		            if(counter == limit) counter = 0;
		          }, timer);
		        },
		        animateItem: function(counter) {
		          var offsetTop = 50;
		          var item = $('#facebook-feed div.item:eq(' + counter + ')');
		          var container = $('#facebook-feed div.animation');
		          if (debug) console.log(container);
		          var height = item.height();
		          if (debug) console.log(height);
		          item.css('height', height);
		          
		          //var offset = (20 * counter);
		          item.find('div.inner').fadeOut(200, function() {
		            container.animate({
		              top: '-=' + (height + (10)) + 'px'
		            }, 400, 'easeOutQuad', function() {
		              var clone = item.clone()
		              item.empty();
		              clone.find(".inner").show(); 
		              container.append(clone);
		            });
		          });
		        },
		        renderHTML: function(item) {
		            var item = $('<div class="item"><div class="inner"><img src="http://graph.facebook.com/' + item.from.id + '/picture" /><p><a>' + item.from.name + '</a> <span>' + item.message + '</span> <span class="date"> - ' + this.prettyDate(item.created_time) + '</span></p></div></div>');
		            $('#facebook-feed div.animation').append(item);
		        }, 
		        prettyDate: function(time) {
		            var date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ").replace("+0000","")),
		            diff = (((new Date()).getTime() - date.getTime()) / 1000),
		            day_diff = Math.floor(diff / 86400);
		              
		          if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 )
		            return;
		              
		          return day_diff == 0 && (
		              diff < 60 && "just now" ||
		              diff < 120 && "1 minute ago" ||
		              diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
		              diff < 7200 && "1 hour ago" ||
		              diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		            day_diff == 1 && "Yesterday" ||
		            day_diff < 7 && day_diff + " days ago" ||
		            day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
		        }
			}; //End facebook feed obj
		
		    facebook.getFeed();
		        
		// mousedown on Movie item
    $("#videoPic img").click(function(){
			$("#galleryMovieLayer").html("<div id='showVidWrapper' class='showVidWrapper'></div>");
			
			var currentid = ($(this).attr('rel'));
      
      var nextVid = ($(this).parent().parent().parent().next().find("#videoPic img").attr('rel'));
      var prevVid = ($(this).parent().parent().parent().prev().find("#videoPic img").attr('rel'));
      
      $("#vidMeny .N").attr('rel',nextVid);
      $("#vidMeny .P").attr('rel',prevVid);
      
      if(nextVid == null){
        nextVid = ($(this).parent().parent().parent().first().find("#videoPic img").attr('rel'));
        $("#vidMeny .N").attr('rel',nextVid);
      }
      if(prevVid == null){
        prevVid = ($(this).parent().parent().parent().siblings().last().find("#videoPic img").attr('rel'));
        $("#vidMeny .P").attr('rel',prevVid);
      }
      
			var params = { allowScriptAccess: "always", wmode: "transparent" };
			var atts = { id: "myytplayer" };
			swfobject.embedSWF("http://www.youtube.com/v/" + currentid + "?enablejsapi=1&playerapiid=ytplayer&version=3", 
	                      "showVidWrapper", "768", "457", "8", null, null, params, atts);

			$("#galleryShowLayer").show();
			//console.log("Movie has been clicked");
			
    	});		
    	//close Movie
      $("#vidMenyClose a").click(function(){
        $("#galleryShowLayer").hide();
        if (debug) console.log("ShowLayer has been closed");
      });
      
      //next Movie
      $("#vidMeny .N").click(function(){
        $("#galleryMovieLayer").html("<div id='showVidWrapper' class='showVidWrapper'></div>");
        var currentId = ($(this).attr('rel'));
        
        var nextVid = ($("#"+currentId).next().attr('id'));
        var prevVid = ($("#"+currentId).prev().attr('id'));
      
        $("#vidMeny .N").attr('rel',nextVid);
        $("#vidMeny .P").attr('rel',prevVid);
      
        if(nextVid == null || nextVid == ""){
          nextVid = ($("#"+currentId).siblings().first().attr('id'));
          $("#vidMeny .N").attr('rel',nextVid);
        }
        if(prevVid == null || nextVid == ""){
          prevVid = ($("#"+currentId).siblings().last().attr('id'));
          $("#vidMeny .P").attr('rel',prevVid);
        }
        
        var params = { allowScriptAccess: "always", wmode: "transparent" };
        var atts = { id: "myytplayer" };
        swfobject.embedSWF("http://www.youtube.com/v/" + currentId + "?enablejsapi=1&playerapiid=ytplayer&version=3", 
                        "showVidWrapper", "768", "457", "8", null, null, params, atts);
        
        if (debug) console.log("Next movie has been selected");
      });
      //previous Movie
      $("#vidMeny .P").click(function(){
        $("#galleryMovieLayer").html("<div id='showVidWrapper' class='showVidWrapper'></div>");
        var currentId = ($(this).attr('rel'));
        
        var nextVid = ($("#"+currentId).next().attr('id'));
        var prevVid = ($("#"+currentId).prev().attr('id'));
      
        $("#vidMeny .N").attr('rel',nextVid);
        $("#vidMeny .P").attr('rel',prevVid);
      
        if(nextVid == null || nextVid == ""){
          nextVid = ($("#"+currentId).siblings().first().attr('id'));
          $("#vidMeny .N").attr('rel',nextVid);
        }
        if(prevVid == null || nextVid == ""){
          prevVid = ($("#"+currentId).siblings().last().attr('id'));
          $("#vidMeny .P").attr('rel',prevVid);
        }
        
        var params = { allowScriptAccess: "always", wmode: "transparent" };
        var atts = { id: "myytplayer" };
        swfobject.embedSWF("http://www.youtube.com/v/" + currentId + "?enablejsapi=1&playerapiid=ytplayer&version=3", 
                        "showVidWrapper", "768", "457", "8", null, null, params, atts);
        
        if (debug) console.log("Previous movie has been selected");
      });
		
		if (debug) console.log("jQuery - End document redy");
	});
	
})($j);

/*SiFR Replacement*/
var din = {
    src: 'wp-content/themes/vt/gui/flash/sifr-din.swf'
    ,ratios: [6,1.41,9,1.35,15,1.29,21,1.25,22,1.22,27,1.24,29,1.21,34,1.22,41,1.21,45,1.2,46,1.21,59,1.2,68,1.19,69,1.2,96,1.19,97,1.18,102,1.19,103,1.18,107,1.19,108,1.18,112,1.19,114,1.18,116,1.19,120,1.18,121,1.19,1.18]
  };

  // You probably want to switch this on, but read <http://wiki.novemberborn.net/sifr3/DetectingCSSLoad> first.
  sIFR.useStyleCheck = true;
  sIFR.activate(din);

  sIFR.replace(din, {
    selector: 'h1',css: ['.sIFR-root { color: #000000 }'], wmode: 'transparent'
  });
  
 	  

  
