$(document).ready(function() {
  
/* Apply background image for service nav
-------------------------------------------------------- */
  
  if($("#mde11-services-menu").length) {
     $("#mde11-services-menu a").each(function() {
         $(this).css("cssText","background:url("+$(this).attr('rel').replace(/ /g,"%20").replace(/'/g,"%27").replace("(","%28").replace(")","%29")+") no-repeat");
     });
  }
  
/* Clear default form value on focus
-------------------------------------------------------- */
 
   $('input:text').each(function() {
       var oldval = $(this).val();
       $(this).focus(function(){
          var newval = $(this).val();
          (($(this).val() == oldval))?$(this).attr('value',''):$(this).val(newval);
       });
       $(this).blur(function(){
          var newval = $(this).val();
          (($(this).val() == ''))?$(this).attr('value',oldval):$(this).val(newval);
       });
   });
  
   //Validate default value
   $.validator.addMethod(
     'text', function (value, element) {
        return value !== element.defaultValue;
     }, 'Please enter a value.'
   );
  
/* Project Ajax gallery
-------------------------------------------------------- */
  
  if(("#mde11-home-projects").length) {
  
   //ajax call
   $("#mde11-home-projects .item").click(function() {
        var self = $(this);
        $("#mde11-popup #html,#mde11-popup #close").hide();
        $.get('/relay.php?ejaxKey=PublicAjaxPageRunner.run&url='+$(this).attr("rel")+'&amp;tpid=111',{}, function(data) {       
              //inject html
              $("#mde11-popup #html").html(data).fadeIn();
              //display it
              $("#mde11-popup #close").fadeIn();   
              //gallery text
              $(".info-pane h2").html(self.find(".title").html());
              $(".info-pane span").html(self.find(".desc").html());
              $(".info-pane").slideDown(250);            
        });
   });    
   
   //close button
   $("#mde11-popup #close").click(function() {
       $("#mde11-popup #html,#mde11-popup #close").fadeOut();
   });
    
   //truncate
   $("#mde11-home-projects h3").each(function() {
       ($(this).html().length>22)? $(this).html($(this).html().substring(0,22)):false;
   });
   $("#mde11-home-projects span").each(function() {
       ($(this).html().length>60)? $(this).html($(this).html().substring(0,60)+"..."):false;
   }); 
   }
  
/* Hide project side menu
-------------------------------------------------------- */  
  
  ($("#mde11-main-menu a[href='/projects/']").hasClass("active"))?$(".side-menu").hide():false;
  
//close .ready()  
});



/* Photo Gallery
------------------------------------------------------- */

function carousel(totalperpage,spacing,containerwidth) {
  
  $('.the-carousel-gallery').each(function()
  {
    //Carousel
    var total = $(this).find('.item').length;
    var items = $(this).find('.item');
    var itemsperpage = totalperpage;
    var total2 = Math.ceil(total / itemsperpage);
    var slideshow_width =  containerwidth || $(this).find('.navigation').width();
    var total_width = total2 * slideshow_width;
    var first = $(this).find('.item:first');
    var npos = 0;
    var padding = spacing || 0;
    var n = 0;
    var p = 0;

    //Create carousel thumbnails
    if($(this).find(".small").length) {
       $(this).find(".thumb,.thumb-link").each(function(i){   
           $(this).css("cssText","background:url("+$(this).find('.small').attr('src').replace(/ /g,"%20").replace(/'/g,"%27").replace("(","%28").replace(")","%29")+") no-repeat 50% 50%");
       });  
    }
    
    //Add a wrapper every X items
    if($(this).parent("#mde11-gallery").length) {
       for(var i = 0; i < total; i+=itemsperpage) {
          items.slice(i, i+itemsperpage).wrapAll("<div class='wrapper'></div>");
       }
    }
    
    //Navigation for thumbnails
    $(this).find('.prev').unbind('click').bind('click',function(e) {
      e.preventDefault();
      npos--;
      if(npos < 0) npos = 0;
      (!Modernizr.csstransitions)?$(this).parents('.the-carousel-gallery').find('.screen').stop().animate({left:npos * -(slideshow_width+padding)}, 350):$(this).parents('.the-carousel-gallery').find('.screen').css({"left":npos * -(slideshow_width+padding)});
      
      //update pagination 
      $(this).parents('.the-carousel-gallery').find(".itemLI.active").removeClass("active");
      $(this).parents('.the-carousel-gallery').find(".itemLI").eq(npos).addClass("active");
    });
    
    $(this).find('.next').unbind('click').bind('click',function(e) {
      e.preventDefault();
      npos++;
      if(npos >= total2) npos = total2-1;
      (!Modernizr.csstransitions)?$(this).parents('.the-carousel-gallery').find('.screen').stop().animate({left:npos * -(slideshow_width+padding)}, 350):$(this).parents('.the-carousel-gallery').find('.screen').css({"left":npos * -(slideshow_width+padding)});
      
      //update pagination
      $(this).parents('.the-carousel-gallery').find(".itemLI.active").removeClass("active");
      $(this).parents('.the-carousel-gallery').find(".itemLI").eq(npos).addClass("active");
    });
    
    //Navigation for image pane
    $(this).find('.next-pane').unbind('click').bind('click',function() {
         p = 0;
         $(this).parent().find(".thumb.active").parent().next().find(".thumb").click();
         if(n==1) {      
           $(this).parent().find(".next").click();
           $(this).parent().find(".thumb.active").parents(".wrapper").next().find(".thumb:first").click();
           n=0;
         }
         $(this).parent().find(".wrapper").each(function() {
           ($(this).find(".thumb:last").hasClass("active"))?n=1:false;
         });
    });
    $(this).find('.prev-pane').unbind('click').bind('click',function() {
         n = 0;
         $(this).parent().find(".thumb.active").parent().prev().find(".thumb").click();
         if(p==1) {      
           $(this).parent().find(".prev").click();
           $(this).parent().find(".thumb.active").parents(".wrapper").prev().find(".thumb:last").click();
           p=0;
         }
         $(this).parent().find(".wrapper").each(function() {
           ($(this).find(".thumb:first").hasClass("active"))?p=1:false;
         });

    });
   
    //Update gallery pane on click
    if($(this).find(".img-pane").length) {
    $(this).find(".thumb").unbind('click').bind('click',function(e) {
       e.preventDefault();

       $(this).parents(".navigation").parent().prev().find("img").hide().load(function() {
            $(this).fadeIn();
       }).attr("src",$(this).find("img").attr("url"));
      
       /*
       if($(this).find("img").attr("alt")!=''&&$(this).find("img").attr("desc")!="") {
       //text
       $(this).parents(".the-carousel-gallery").find(".info-pane h2").html($(this).find("img").attr("alt"));
       $(this).parents(".the-carousel-gallery").find(".info-pane span").html($(this).find("img").attr("desc"));
       $(".info-pane").slideDown(200);
       } else {
       $(".info-pane").slideUp(200);  
       }*/
      
       $(this).parents(".the-carousel-gallery").find(".thumb").removeClass("active");
       $(this).addClass("active");
      
    });  
    }
    
    //Pagination
    if($(this).find(".pagination").length) {
       for( i=0; i < total2; i++) {
          $("<li class='itemLI' rel="+i+"></li>").appendTo($(this).find("ul"));  
       };  
    
       $(this).find(".itemLI:first").addClass("active");
  
       $(this).find(".itemLI").live('click',function() {
          var pos = $(this).attr("rel");
    
          $(this).parents('.the-carousel-gallery').find(".itemLI.active").removeClass("active");
          $(this).addClass("active");
          $(this).parents('.the-carousel-gallery').find('.screen').stop().animate({left:pos * -(slideshow_width+5)}, 350);
       });
      
       //Remove pagination if there's only one page
       $(".pagination").each(function() {
          if($(this).find(".itemLI").length ==1) {
             $(this).hide();
          }
       });
    } 
                                  
    //Init
    $(this).find(".thumb:first").click();
    
  //end each()  
});  

}

var openPopup = window.open;

function show_msg(msg) { alert(msg); }

function validateForm() {
	missing_required = 0;

	for (i = 0; i < arguments.length; i++) {
		if(arguments[i] == '') {
			missing_required = 1;
		}
	}

	if(missing_required) {
		alert("A required form field is missing.");
		return false;
	} else {
		return true;
	}
}

function expCustomLink(myURL) {
	location.href = myURL;
}

function setUrl(path) {
	document.location.href = path;
}

function expArticleLink(sectionId, articleId) {
	location.href = '/index.php?section_id=' + sectionId + '&section_copy_id=' + articleId;
}

function expPopupWindow(url, widthVal, heightVal, resizableVal, scrollbarsVal, toolbarVal, locationVal, directoriesVal, statusVal, menubarVal, copyHistoryVal) {

	var attributes = "width="  	 	 + widthVal       +
				 	 ",height=" 	 + heightVal      +
				 	 ",resizable="  + resizableVal  +
				 	 ",scrollbars="  + scrollbarsVal  +
				 	 ",toolbar=" 	 + toolbarVal 	  +
				 	 ",location=" 	 + locationVal 	  +
				 	 ",directories=" + directoriesVal +
				 	 ",status=" 	 + statusVal 	  +
				 	 ",menubar=" 	 + menubarVal 	  +
				 	 ",copyhistory=" + copyHistoryVal;

	window.open(url, 'WindowName', attributes);
}

function xprLog(msg) {
    if (window.console) console.log(msg);
}

if (document.addEventListener) {  
    document.addEventListener("DOMContentLoaded", function () { if (typeof onXprPageLoad == 'function') onXprPageLoad(); }, false);
} else if (document.attachEvent) {  
    document.attachEvent('DOMContentLoaded', function () { if (typeof onXprPageLoad == 'function') onXprPageLoad(); });
}  

