/*************** JQUERY EXTENSIONS ****************/

(function($){
    // equals method
    jQuery.fn.equals = function(selector) {
        return $(this).get(0)==$(selector).get(0);
    };
    // preload images
    jQuery.fn.preload = function() {
        this.each(function(){
            $('<img/>')[0].src = this;
        });
    }
})(jQuery);

/****************** GA TRACKING ******************/

gaPageTrack = function(p) {
    if( typeof( _gaq ) != 'undefined' ) {
        _gaq.push(['_trackPageview', p]);
    }
};

gaEventTrack = function(category,action) {
    if( typeof( _gaq ) != 'undefined' ) {
        if( typeof( pname ) != 'undefined' ) {
            _gaq.push(['_trackEvent',category,action,'Page',pname]);
        } else {
            _gaq.push(['_trackEvent',category,action]);
        }
    }
};

/*************** COMMON FUNCTIONS ****************/

// get current facebook user info
getFBUser = function() {
	FB.getLoginStatus(function(response) {
		  if (response.authResponse) {
			  FB.api('/me', function(response) {
	        		if(typeof response.error == "undefined") {
	        			$('#header-user-name').text(response.first_name + " " + response.last_name);
	        		}
	        	});
		  }
	});
};

// facebook login
doFacebookLogin = function() {
    FB.login(function(response) {
        if (response.authResponse) {
            gaEventTrack('Booshaka','User Login');
            window.location.reload();
        }
    }, {
        scope:'email,user_likes,friends_likes'
    });
};

// share page
sharePage = function(link, picture, name, caption, description, message) {
    FB.ui({
        method: 'feed',
        link: (typeof(link) != 'undefined' && link ? link : document.location.href),
        picture: (typeof(picture) != 'undefined' && picture ? picture : ('https:' == document.location.protocol ? ctxhssl : ctxh) + '/images/n/logo.png'),
        name: (typeof(name) != 'undefined' && name ? name : ''),
        caption: (typeof(caption) != 'undefined' && caption ? caption : ''),
        description: (typeof(description) != 'undefined' && description ? description : ''),
        message: message
    },
    function(response) {
        if (response && response.post_id) {
            gaEventTrack('Facebook','Share');
            alert('Your post published successfully.');
        }
    });
};

invitePage = function(returnUrl, title, message, to, filters) {
    FB.ui({
        method: 'apprequests',
        message: (typeof(message) != 'undefined' && message ? message : 'Join me and see where you rank on Facebook'),
        title: (typeof(title) != 'undefined' && title ? title : 'Invite your friends to Booshaka!'),
        data: (typeof(returnUrl) != 'undefined' && returnUrl ? returnUrl : document.location.href),
        to: (typeof(to) != 'undefined' && to ? to : ''),
        filters: (typeof(filters) != 'undefined' && filters ? filters : '')
    },
    function(response) {
        if (response && response.request_ids) {
            gaEventTrack('Facebook','Invite');
            alert('You invitation requests were sent successfully.');
        }
    });

};

shareLeaderboardTab = function(pageName,pageId,link,appId) {
    FB.ui({
        method: 'stream.publish',
        name: pageName + ' Top Fans',
        link: link + '?sk=app_' + appId,
        picture: ('https:' == document.location.protocol ? ctxhssl : ctxh) + '/images/n/logo.png',
        caption: 'See your ranking and most recent activity',
        target_id: pageId
    },
    function(response) {
        if (response && response.post_id) {
            gaEventTrack('Facebook','ShareLeaderboard');
            alert('Your post published successfully.');
        }
    }
    );
};

activateHeaderAccountLinks = function() {
    var welcomeDiv = $('#welcome-logged-in');
    if (welcomeDiv) {
        $('.name', welcomeDiv).click(function() {
            $('.wrapper', welcomeDiv).toggleClass('active');
        });
        $('.wrapper', welcomeDiv).mouseleave(function() {
            $(this).removeClass('active');
        });
    }
};

hasPermissions = function(requiredPerms, callBackFunction) {
    FB.login(function(response) {
        if (response.authResponse) {
            FB.api('/me/permissions', function(perms_response) {
            	var missingRequirements = null;
            	
            	var permissionsList = perms_response['data'][0];
            	var requiredPermissionsArray = requiredPerms.split(',');
            	var requiredPermissionsFound = 0;

            	for (var i = 0; i < requiredPermissionsArray.length; i++) {
            		var requirement = $.trim(requiredPermissionsArray[i]);
            		if (!permissionsList[requirement]) {
            			if (!missingRequirements) {
            				missingRequirements = requirement;
            			}
            			else {
            				missingRequirements += ', ' + requirement;
            			}
            			break;
            		}
            		else {
            			requiredPermissionsFound++;
            		}
            	}
            	
            	if (requiredPermissionsFound == requiredPermissionsArray.length) {
            		callBackFunction(true, missingRequirements);
            	}
            	else {
            		callBackFunction(false, missingRequirements);
            	}
            });
        }
    }, {
        scope:requiredPerms
    });
}

registerUser = function() {
    $.ajax({
        type:'GET',
        url:ctxp+'/xhr/registerUser',
        success:function(data,textStatus){},
        error:function(XMLHttpRequest,textStatus,errorThrown){}
    });
}

/******************* DIALOG *******************/

var dialog;

/* stretch background overlay to cover the content - doesn't do it automatically */
$(document).bind('cbox_load', function() {
    var doc = $(document);
    $('#cboxOverlay').height(doc.height()).width(doc.width());
});

closeDialog = function() {
    if (dialog) {
        dialog.colorbox.close();
    }
};

openDialog = function(href,height,width) {
    width = typeof(width) != 'undefined' ? width : 677;
    height = typeof(height) != 'undefined' ? height : 196;
    dialog = $.colorbox({
        opacity:.5,
        transition:'none',
        iframe:true,
        scrolling:true,
        width:width,
        height:height,
        href:href,
        fastIframe:false
    });
}

openSelectPageDialog = function(type) {
    openDialog(ctxp+'/select-page' + (typeof(type)!='undefined' ? '?register=' + type : ''), 196, 500);
}

/******************* PAGE INIT *******************/

$(function() {

    // ajax opts
    $.ajaxSetup({
        timeout:30000
    });
    
    // preload 'hover' images
    $([ctxp+'/images/n/arrow-right.png',ctxp+'/images/share-hover.png',ctxp+'/images/get-started-hover.png']).preload();

    // populate user name on page (if appl)
    getFBUser();

    // activate account links in header
    activateHeaderAccountLinks();

    // attach logout event
    FB.Event.subscribe('auth.logout', function(response) {
        gaEventTrack('Booshaka','User Logout');
    });
    
    // attach logout event
    FB.Event.subscribe('auth.login', function(response) {
    	setTimeout("registerUser()",1000);
    });

    // set up account dropdown links
    $('.choose-pages-link').click(function() {
        FB.getLoginStatus(function(response) {
            if (response.authResponse) {
                openSelectPageDialog();
            }
            else {
                FB.login(function(response) {
                    if (response.authResponse) {
                        openSelectPageDialog();
                    }
                }, {
                    scope:'email,manage_pages,offline_access'
                });
            }
        });
        return false;
    });
    $('#logout').click(function() {
    	FB.logout(function(response) {
    		window.location=ctxp+"/logout";
    	});
        return false;
    });
});


