/* Author: Rob @ JPCreative

*/

// Flag dropdown


// jquery replace plugin :)
	$.fn.replace = function(o) { 
		return this.after(o).remove().end(); 
	};


$(function(){
	
	x = false;
	
	$('.current-locale').click(function() {
		if (x == false) {
			$(this).parent().parent().removeClass('dormant');
			$(this).find('span').empty().append('English');
			
			x = true
		}
	
		else {
			$(this).parent().parent().addClass('dormant');
			$(this).find('span').empty().append('Choose language');
			x = false
		}
	});
});

// end of flag dropdown

// Grayscale icon code

$(document).ready(function(){
	
	takemycolour();
	
	function takemycolour()
	{
		var imgObj = document.getElementById('active');
		
		if (imgObj == null)
		{
           	return;
        }
            
		else
		{
           	if($.browser.msie)
        	{
                grayscaleImageIE(imgObj);
            } 
            
            else
            {
                imgObj.src = grayscaleImage(imgObj);
            }              
                        
        }
         
    }
    
    
    
    
	$(".publish-checkbox").click(function(e){
//		var	admin_base_url = document.URL.split("/admin/cms/page/")[0] + "/";
		var	admin_base_url = "/admin/";
		var target = e.target;
		var jtarget = $(target);
		var pageId = $(this).attr("name").split("status-")[1];
		reloadItem(jtarget, admin_base_url + "cms/page/" + pageId + "/change-status/", { 1:1 });
		return true;
	});

	//Youtube embedding code
	
	var vidWidth = 425;
	var vidHeight = 344;

	var obj = '<object width="' + vidWidth + '" height="' + vidHeight + '">' +
		'<param name="movie" value="http://www.youtube.com/v/[vid]&hl=en&fs=1">' +
		'</param><param name="allowFullScreen" value="true"></param><param ' +
		'name="allowscriptaccess" value="always"></param><em' +
		'bed src="http://www.youtube.com/v/[vid]&hl=en&fs=1" ' +
		'type="application/x-shockwave-flash" allowscriptaccess="always" ' +
		'allowfullscreen="true" width="' + vidWidth + '" ' + 'height="' +
		vidHeight + '"></embed></object> ';

	$('.blog_content p:contains("youtube.com/watch")').each(function(){
		var that = $(this);
		var vid = that.html().match(/(?:v=)([\w\-]+)/g); // end up with v=oHg5SJYRHA0
		if (vid.length) {
			$.each(vid, function(){
				that.html( obj.replace(/\[vid\]/g, this.replace('v=','')) );
			});
		}
	});

});

function reloadItem(el, url, data, callback, errorCallback) {
		if (data === undefined) data = {};
	
		function onSuccess(response, textStatus) {
			//if (callback) { callback(response, textStatus); }
			//window.location.reload();
			alert("Changes published.")
		}
		
		function onError(XMLHttpRequest, textStatus, errorThrown) {
			if (errorCallback) errorCallback(XMLHttpRequest, textStatus, errorThrown);
		}
		var answer = confirm("Are you sure you want to publish changes?")
		if (answer){
		
		$.ajax({
			'data': data,
			'success': onSuccess,
			'error': onError,
			'type': 'POST',
			'url': url,
			'xhr': (window.ActiveXObject) ? function(){try {return new window.ActiveXObject("Microsoft.XMLHTTP");} catch(e) {}} : function() {return new window.XMLHttpRequest();}				
		});			
	}
	else{
		alert("Published canceled.")
		window.location.reload()
	}
		
		
	}




    function grayscaleImageIE(imgObj)
    {
        imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
    }

    function grayscaleImage(imgObj)
    {
        var canvas = document.createElement('canvas');
        var canvasContext = canvas.getContext('2d');
        
        var imgW = 168;
        var imgH = 168;
        canvas.width = imgW;
        canvas.height = imgH;
        
        canvasContext.drawImage(imgObj, 0, 0);
        var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
        
        for(var y = 0; y < imgPixels.height; y++){
            for(var x = 0; x < imgPixels.width; x++){
                var i = (y * 4) * imgPixels.width + x * 4;
                var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
                imgPixels.data[i] = avg; 
                imgPixels.data[i + 1] = avg; 
                imgPixels.data[i + 2] = avg;
            }
        }
        
        canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
        return canvas.toDataURL();
    }


// end of grayscale code

// FAQ scroller code

var GblTop;

function GetVertOffset (srchStr)
{
    GblTop = $(srchStr).offset().top - parseFloat($(srchStr).css('marginTop').replace(/auto/, 0));
}

$(document).ready(function ()
{
	
  // Append FAQs to left column on FAQ page	
 
if ($('.questions-container').length) {
  $('div.answer').each(function(){
       $('ul.questions').append('<li><a href="#'+$(this).find('a').attr('name')+'">'+$(this).find('h3').html()+'</a></li>')
  });	  
}

// Contact us append to rght anchors
if ($('.contact-seperator').length) {
  $('div.contact-seperator').each(function(){
       $('ul.region-breakdown').append('<li><a href="#'+$(this).find('a').attr('name')+'">'+$(this).find('h2').html()+'</a></li>')
  });	  
}


/*addressURL = location.pathname.split("/");

$('a.contact-region-button').each(function(){
	aURL = $(this).attr('href').split("/");
	 
	//alert(addressURL[2]);
	alert(aURL[aURL.length-1]+ " " + aURL.length);
	
	//if ($(this).attr('href').indexOf(thisUrl[1]) != -1) {
	//	$(this).addClass('active-'+$(this).attr('class'))
	//}
});*/



if ( $('.questions-container').length ) {
	GetVertOffset ('.questions-container');     //-- Sets GblTop

    $(window).scroll (function ()
    {
        // what is the y position of the scroll?
        var y = $(window).scrollTop();
        // whether that's below the start of article?
        if (y >= GblTop)
        {
            // if so, add the fixed class
            $('.questions-container').addClass('fixed');
        }
        else
        {
            // otherwise, remove it
            $('.questions-container').removeClass('fixed');
        }
    });
}
    

});








