/***********************
*  Site Specific JS   *
************************/

//Javascripts
$(document).ready(function(){
  $.favicon('http://cdn.myld.com.au/2/896/ypm-group-your-property-match_f1b59f263f.ico','http://cdn.myld.com.au/2/892/ypm-group-your-property-match_fc87e9037a.png');
  //$("a[href='partneragent-login']").attr('href', 'http://www.ypmportal.com.au/Home/Login');
  //$('.menu_link_5').attr('target', '_blank');

  menu.contactDetails({
    phone: '1300088949',
          //optional, can have multiple values['0752212345', ['Head Office', '0752212345']]
    email: 'info@ypmgroup.com.au',
          //optional, can have multiple values['email@gmail.com', ['Support', 'support@yahoo.com']]
    address: 'Office 1, L2, 510 Saint Pauls Terrace, Bowen Hills, QLD 4006',
					//optional, can have multiple values['Robina, QLD', ['Southport', 'Southport, QLD']]
	});

	//mobile nav
	$('<li><a href="https://www.instagram.com/ypm_group/" target="_blank">Instagram</a></li><li><a href="https://www.linkedin.com/company/ypm-group" target="_blank">Linkedin</a></li>').insertAfter('#jmm-right > ul > li.jmm-sm > ul > li:eq(0)');
	
	$('#jmm-right > ul > li:eq(2) a').replaceWith('<a href="http://maps.google.com/maps?q=Shop%206%2F27%20Cunningham%20St%2C%20Newstead%2C%20QLD%2C%204006" target="_blank"><i class="icon-address icon"></i> Shop Address</a>');
	
	
	$('<li><a href="javascript:void(0)" target="_blank"><i class="icon-address icon"></i> PO Box 575, Clayfield, QLD 4011</a></li>').insertAfter('#jmm-right > ul > li:eq(2)');

	//cta link
	$('#ctaLink1').replaceWith('<a href="tel://1300088949">1300 088 949</a>');

	//slider
	/*$("#slideShow").backstretch([
		"http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_c9490337d3.jpg",
		"http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_8b2933f7da.jpg",
		"http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_4f4149a721.jpg",
		"http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_8044f398ed.jpg",
		"http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_ac2588643c.jpg",
		"http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_c1746cdc5a.jpg"
	], {duration: 5000, fade: 750, random: true});
	
	var items = [
				{ img: "http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_c9490337d3.jpg", caption: "Full circle project marketing services"},
				{ img: "http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_4f4149a721.jpg", caption: "Innovative & dynamic sales strategies"},
				{ img: "http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_8044f398ed.jpg", caption: "Experienced & passionate sales team"},
				{ img: "http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_8b2933f7da.jpg", caption: "Full circle project marketing services"},
				{ img: "http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_ac2588643c.jpg", caption: "Live sales portal - 24/7 access to files & pricing"},
				{ img: "http://cdn.myld.com.au/2/1451/ypm-group-your-property-match_c1746cdc5a.jpg", caption: "Live sales portal - instant reservation system"}
		];

		var options = {
				fade: 1000,
				duration: 4000,
				random: true
		};

		var images = $.map(items, function(i) { return i.img; });
		var slideshow = $.backstretch(images,options);

		$('#slideShow').on("backstretch.show", function(e, instance) {
				var theCaption = items[instance.index].caption;
				$(".backstretch-caption").text(theCaption).addClass('showMe',1000);
		});
		$('#slideShow').on("backstretch.before", function(e, instance) {
			$(".backstretch-caption").removeClass('showMe',1000);
		});*/

	//fancybox
	/* Apply to single image */
			$("a.fancybox").fancybox();

	/* Apply fancybox to multiple items */
			$("a.fancybox[rel='gallery_group']").fancybox({
					'transitionIn'    :    'elastic',
					'transitionOut'    :    'elastic',
					'speedIn'        :    600,
					'speedOut'        :    200
			});

	/* Apply with thumbnails visible */
			if ($('body#property-calculator').is('*')) {
				$("a.fancybox").fancybox({
					helpers : {
						thumbs : {
							width: 200,
							height: 200
						},
						overlay : {
							closeClick : false
						}
					}
				});
			}
			else {
				$("a.fancybox").fancybox({
					helpers : {
						thumbs : {
							width: 200,
							height: 200
						}
					}
				});
			}

		$(".tcLink").fancybox({
			closeClick  : false, // prevents closing when clicking INSIDE fancybox
			openEffect  : 'none',
			closeEffect : 'none',
			helpers   : {
			 overlay : {closeClick: false} // prevents closing when clicking OUTSIDE fancybox
			}
		 }).trigger("click");

		 $( ".iagree" ).click(function() {
				$.fancybox.close()
			});

});

$(window).load(function(){
		//match
		$('.match').matchHeight();
		$('.homeThumb h3').matchHeight();

		//cta
		 $("#cta").backstretch([
			"http://cdn.myld.com.au/2/886/your-property-match_e1fca34573.jpg",
			"http://cdn.myld.com.au/2/886/your-property-match_8237a06532.jpg"
		], {duration: 200, fade: 150, random: false});
		$('#cta').backstretch("pause");
		$(".trigger").hover(
				 function () {
					 $('#cta').backstretch("show",1);
				 },
				 function () {
					 $('#cta').backstretch("show",0);
				 }
		 );
});

		$('#slogan').prependTo('#slideShow');
		$('#slogan div').removeClass('container');
//		$('#pageTitle').prependTo('#slideShow');
    $('#pageTitle').prependTo('#carousel-example-generic');
  //  $('.menu_link_5').attr("href", "http://portal.ypmgroup.com.au");
  //  $('.menu_link_5').attr("target", "_blank");
    //$('ul.nav').children().eq(4).addClass('insert-portal');
    //$('li.menu_link_5_insert').insertAfter('li.insert-portal');


//form validation
$('#custom_form').smartCaptcha({
  validateText: ["name", "message", "number"],
  validateEmail: ["email"],
  redirectLink: null,
	validateStyle: "default"
});

//view section 1
$('#view_section_1').insertAfter('#slideShow');

//error div
$('#error').insertAfter('#slideShow');

//justify nav
$('.navbar .nav').addClass('nav-justified');

//nav breaks
var html = $(".navbar .navbar-nav > li > a").eq(3).html();
html = html.substring(0, 8) + "<br>" + html.substring(8);
$(".navbar .navbar-nav > li > a").eq(3).html(html);

/*var html = $(".navbar .navbar-nav > li > a").eq(5).html();
html = html.substring(0, 8) + "<br>" + html.substring(8);
$(".navbar .navbar-nav > li > a").eq(5).html(html);*/

var html = $(".navbar .navbar-nav > li > a").eq(6).html();
html = html.substring(0, 10) + "<br>" + html.substring(10);
$(".navbar .navbar-nav > li > a").eq(6).html(html);

//subnav
$('.navbar .navbar-nav > li').eq(1).addClass('dropdown').append('<ul class="dropdown-menu">'+
      '<li><a href="about-us#industry-expertise">Industry Expertise</a></li>'+
    '</ul>').children('a').addClass('dropdown-toggle');

$('.navbar .navbar-nav > li').eq(2).addClass('dropdown').append('<ul class="dropdown-menu">'+
      '<li><a href="projects#current-projects">Current Projects</a></li>'+
      '<li><a href="projects#coming-soon">Up-and-coming Projects</a></li>'+
      '<li><a href="projects#pastBox">Past Projects</a></li>'+
    '</ul>').children('a').addClass('dropdown-toggle');
menu.reset();

//Detect mac
	var Browser = menu.browserDetect('version');
		if (Browser.OS == 'Mac') {
		$('body').addClass('mac');
}

//
//YPM Group - Blogger v3 News Feed Generator
//

// Returns a long month string based on an Int input of range 0-11 (received from a Date.getMonth() return)
function numToMonth(num) {
    var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    return months[num];
}


// Returns a short month string based on an Int input of range 0-11 (received from a Date.getMonth() return)
function numToShortMonth(num) {
        var month = '';

        switch (num) {
            case 0:
                month = "Jan";
                break;
            case 1:
                month = "Feb";
                break;
            case 2:
                month = "Mar";
                break;
            case 3:
                month = "Apr";
                break;
            case 4:
                month = "May";
                break;
            case 5:
                month = "Jun";
                break;
            case 6:
                month = "Jul";
                break;
            case 7:
                month = "Aug";
                break;
            case 8:
                month = "Sep";
                break;
            case 9:
                month = "Oct";
                break;
            case 10:
                month = "Nov";
                break;
            case 11:
                month = "Dec";
                break;
        }

        return month;
    } // End function numToShortMonth(num)


// ************************************
// Change variabls here
// ************************************
if ($('#home').length) {
  var blog_id = "7610118557728791773";
  var api_key = "AIzaSyBKr71oVMChmKqHmD3fpP6Ej-9UzJ20TYg";
  console.log("News page") // Debug
}
if ($('#news').length) {
  var blog_id = "7610118557728791773";
  var api_key = "AIzaSyBKr71oVMChmKqHmD3fpP6Ej-9UzJ20TYg";
  console.log("News page") // Debug
}
if ($('#construction').length) {
  var blog_id = "1927673907425236710";
  var api_key = "AIzaSyCM8u6PjS6k6veQN4ZqqDO8jsj9EFZmq2w";
  console.log("Construction page") // Debug
}

// Create URL from variables above
var ypm_group_blog_api_string = 'https://www.googleapis.com/blogger/v3/blogs/'+blog_id+'/posts?key='+api_key;
var ypm_group_blog_jqHXR = $.getJSON(ypm_group_blog_api_string) // We will be using this plenty later on


.done(function(ypm_group_blog_JSON) {

        if ($('#home').length) { // If we're on the home page (only display minimal information)
            //Loop through each blog post
            console.log(ypm_group_blog_JSON.items)
            var newsData = [];
            var len = ypm_group_blog_JSON.items.length;
            var i;

            //Limit to the two most recent posts
            //if (len > 2) {
            //    len = 2;
            //}

            for (i = 0; i < len; i++) {
                var published_date = new Date(Date.parse(ypm_group_blog_JSON.items[i].published)); //Parse the JSON string (v3 uses ECMAScript 5 ISO-8601 format) to Date prototype
                var summary = ypm_group_blog_JSON.items[i].content.split('<a name=\'more\'></a>');

                newsData.push({
                    date: numToMonth(published_date.getMonth()) + ' ' + published_date.getDate() + ', ' + published_date.getFullYear(),
                    title: ypm_group_blog_JSON.items[i].title,
                    post_id: ypm_group_blog_JSON.items[i].id,
                    post_image: ypm_group_blog_JSON.items[i].content,
                    summary: summary[0]
                });
            }

            $("#newsContent").html($("#newsSuccessTemplate").render(newsData));

            // Use the first image from the blog post as the news post image, otherwise use the default. Also a mild amount of cleanup (to remove some of the cruft Blogger leaves behind)
            for (i = 0; i < len; i++) {
                var imgs = $('#blog' + i + ' img');
                // If there are two or more images in the blog item on the Home page, then the blog content must have an image. Use the first blog image as the main image and remove all others
                if (imgs.length > 1) {
                    imgs[0].src = imgs[1].src;
                    $('#blog' + i + '-content a img').parent().remove();
                }
                $('#blog' + i + '-content div').remove();
            }
						
						$('.newsImageBox').contents(':not(img)').remove();
        }

        if ($('#news, #construction').length) { // If we're on the News page, or the construction page
            $.each(ypm_group_blog_JSON.items, function(i, ypm_group_blog_item){ //Loop through each blog post
              var post_id = ypm_group_blog_item.id //Use the Post ID as a unique identifier
              var published_date = new Date(Date.parse(ypm_group_blog_item.published)); //Parse the JSON string to get published_date (v3 uses ECMAScript 5 ISO-8601 format) to Date prototype
              var published_month = numToShortMonth(published_date.getMonth()); //Get a short month String based off the Date prototype - getMonth returns an Int of range 0-11

              if (i === 0) { //first item
                $('<div role="tabpanel" class="tab-pane active" id="blogFeedItem' + post_id + '"><div class="blogDate">Posted: ' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</div><h3 itemprop="name">' + ypm_group_blog_item.title + '</h3>' + ypm_group_blog_item.content + '</div>').appendTo('#blogFeed');

                $('<li role="presentation" class="active"><a href="#blogFeedItem' + post_id + '" role="tab" data-toggle="tab"><span class="blogDateSub">' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</span>' + ypm_group_blog_item.title + '</a></li>').appendTo('#blogNavTab ul');

                $('#blogFeedItem' + post_id + ' a > img').parent().attr('rel', 'blogFeedItem' + post_id);

                $('#blogFeedItem' + post_id + ' a > img').parent().addClass('fancybox');


              } else { // the other stuff

                $('<div role="tabpanel" class="tab-pane" id="blogFeedItem' + post_id + '"><div class="blogDate">Posted: ' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</div><h3 itemprop="name">' + ypm_group_blog_item.title + '</h3>' + ypm_group_blog_item.content + '</div>').appendTo('#blogFeed');

                $('<li role="presentation" class=""><a href="#blogFeedItem' + post_id + '" role="tab" data-toggle="tab"><span class="blogDateSub">' + published_date.getDate() + ' ' + published_month + ', ' + published_date.getFullYear() + '</span>' + ypm_group_blog_item.title + '</a></li>').appendTo('#blogNavTab ul');
								
								$('#blogNavTab ul li').hide();
								var size_li = $("#blogNavTab ul li").size();
								var x=10;
								$('#blogNavTab ul li:lt('+x+')').show();
								$('#loadMore a').click(function () {
										x= (x+10 <= size_li) ? x+10 : size_li;
										$('#blogNavTab ul li:lt('+x+')').show();
										//if(x == size_li){
										//		$('#loadMore a').hide();
										//}
										return false;
								});

                $('#blogFeedItem' + post_id + ' a > img').parent().attr('rel', 'blogFeedItem' + post_id);

                $('#blogFeedItem' + post_id + ' a > img').parent().addClass('fancybox');

              }
            });

            $('.blogDate').css({
                'color': '#f26329',
                'font-size': '26px',
                'font-weight': '300',
                'line-height': 'normal'
              }); //In-line CSS styling for .blogDate required as the class is not being recognised by browsers

            $('a.fancybox[rel*="blogFeedItem"]').fancybox();

            var hash = window.location.hash;
            if (hash !== '') {
              $('#blogNavTab a[href="' + hash + '"]').tab('show');
              $('html, body').delay(500).animate({
                scrollTop: $(hash).offset().top - 191
              }, 2000);
            }
        }
        // end of news page

    }) //End .done

//Fallback content to be displayed in case the blog is offline; not responding; or over the limit of daily requests
.fail(function() {
  if ($('#home').length) {
    $("#newsContent").html($("#newsFailTemplate").render());
  }

  if ($('#news-links').length) {
    $.each(ypm_group_blog_JSON.items, function(i, ypm_group_blog_item) {
      $('<h1 itemprop="name">News Currently Offline</h1><p item="description">Apologies, the news feed is currently offline. Please contact our staff so we can diagnose and resolve the issue as soon as possible!</p>').appendTo('#blogFeed');
    });
  }

}); 
