//Common JS library - Chris Crocetti, 2/11/2011
//Load hash fragment URLs

$(document).ready(function(){
	$('.ga_event').live('click', function(e){
		_gaq.push(['_setAccount', 'UA-17533052-1']);
		_gaq.push(['_trackEvent', 'Downloads', $(this).attr('rel')]);
	});
	
	//Autograb content on hash fragment url.
	var hash = self.document.location.hash.substring(2);
	if (hash!=''){
		replaceContent(hash);
	}
	//Handle hashable link onclick.
	$('.hashable').click(function(){
		var urlpart = this.pathname.replace(/\//g,''); // 'device-desktop'
		if (urlpart!=''){
			//Send you back to the root if your pathname isn't /
			/*if(location.pathname!="/") {
				window.location="/#/"+urlpart;
				return false; //Stops ajax load attempt 
			}*/
			//replace url
			self.document.location.hash = "#/"+urlpart;
			replaceContent(urlpart);
			$("html").animate({ scrollTop: 0 }, "fast");	
			
			return false; //cancel click
		}

	});
	
	//Faq show/hide
	//setup the FAQs to be closed
	$('#faq .a').hide();
	
	// setup the .q links to open them up
	$('#faq .q').click(function(e){
		e.preventDefault();
		
		if ($(this).hasClass('sel')) {
			$(this).removeClass('sel').next('.a').removeClass('sel').slideUp();
		}
		else {
			$('#faq .q').filter('.sel').removeClass('sel');
			$('#faq .a').filter('.sel').removeClass('sel').slideUp();
			$(this).addClass('sel').next('.a').addClass('sel').slideDown();
		}
	});
	
	$('#logout').click(function(){
		//Run logout API class.
		$.ajax({
			type: "POST",
			url: "/home/logout/",
			data: "auid="+getCookie('c_uid')+"&username="+getCookie('c_username'),
			dataType: "json",
			success: function(data) {
				if(data.result!=0 ){
					alert(data.message);
					$("#error").html("<div class='errorMessage'>Sorry " + data.message+". <a href='/forgetpass/'>Did you forget your password?</a></div>"); 
				} else {
					//Redirect to logged out page.
					document.location = data.goto;
				}
			},
			/*error:function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
                alert(thrownError);
            }*/
			
		});
		return false;
	});
	
	$('#loginButton').click(function(){
		var unamefield = document.getElementById("username");
		//unamefield.focus(); 
		$('#loginButton').unbind('click').click(function(){return false;}); // clear click for dupes
		
		$('#arrow').animate({ rotate : 180 },300);
		$('#arrow').css('left', -30);
		$('#inputContainer').animate({
			left : -410,
			width : 450
		},400,function() { // completed callback
			$('#arrow').css('rotate', 0);
			$('#arrow').attr('src', '/home/lib/s1/images/global/login-arrow-right.png');
			
			$('#loginButton').click(function(){// redefine click function
				//Login handler
				dataString = $("#loginform").serialize();
				var theloginedurl;
				$.ajax({
					type: "POST",
					url: "/home/login/",
					data: dataString,
					dataType: "json",
					success: function(data) {
						if(data.result!=0 ){ 
							$("#error").html("<div class='errorMessage'>Sorry " + data.message+". <a href='/forgetpass/'>Did you forget your password?</a></div>"); 
						} else {
							theloginedurl=data.goto;
							if(data.message.length>0) {
								window.alert(data.message);
								$("#error").html("<div class='successMessage'>" + data.message + " </div>"); 
							} else {
								var t=setTimeout("window.location='"+theloginedurl+"'",100);
							}
						}
					}
				});
				return false;
			});
		});
		return false;
	});
});

/* 
 * JQuery CSS Rotate property using CSS3 Transformations
 * Copyright (c) 2011 Jakub Jankiewicz  <http://jcubic.pl>
 * licensed under the LGPL Version 3 license.
 * http://www.gnu.org/licenses/lgpl.html
 */
(function($) {
    function getTransformProperty(element) {
        var properties = ['transform', 'WebkitTransform',
                          'MozTransform', 'msTransform',
                          'OTransform'];
        var p;
        while (p = properties.shift()) {
            if (element.style[p] !== undefined) {
                return p;
            }
        }
        return false;
    }
    $.cssHooks['rotate'] = {
        get: function(elem, computed, extra){
            var property = getTransformProperty(elem);
            if (property) {
                return elem.style[property].replace(/.*rotate\((.*)deg\).*/, '$1');
            } else {
                return '';
            }
        },
        set: function(elem, value){
            var property = getTransformProperty(elem);
            if (property) {
                value = parseInt(value);
                $(elem).data('rotatation', value);
                if (value == 0) {
                    elem.style[property] = '';
                } else {
                    elem.style[property] = 'rotate(' + value%360 + 'deg)';
                }
            } else {
                return '';
            }
        }
    };
    $.fx.step['rotate'] = function(fx){
        $.cssHooks['rotate'].set(fx.elem, fx.now);
    };
})(jQuery);

/* *** End Rotate Script *** */



function replaceContent(urlpart){
	$('#device_content').load('/home/ajax/'+urlpart+'/');
	$('#device-text-wrapper').load('/home/ajax/'+urlpart+'-text/');
	$('link[rel=canonical]').attr({'href':'http://www.bookmark.com/'+urlpart+'/'});
}

//Cookie management functions
function getCookie(c_name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name){
			return unescape(y);
		}
	}
}
function setCookie(c_name,value,exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value + "; path=/";
}

//Image preloaders
Image1= new Image(130,200);
Image1.src = "/home/lib/s1/images/global/popmenu-bg.png";
Image2= new Image(130,10);
Image2.src = "/home/lib/s1/images/global/popmenu-footer.png";
Image3= new Image(10,18);
Image3.src = "/home/lib/s1/images/global/popmenu-pointer.png";
Image4= new Image(23,23);
Image4.src = "/home/lib/s1/images/global/login-arrow-right.png";
