var is_logged_in = false;
var url = $(location).attr('href');
var baseURL = url.substring(0, url.indexOf('/', 14) ) + "/";
var user = jQuery.parseJSON( $("#user").html() );

for (var key in user) {
   var obj = user[key];
   for (var prop in obj) {
      //log(prop + " = " + obj[prop]);
      if( prop == "domain" ) var domain = 'https://' + obj[prop];
   }
}

$(".help").tooltip({ effect: 'slide', offset: [ 0, 0 ] });	

//log( url );

// if not on the homepage alter the background
if( url != baseURL && url != "http://www.flickfolia.com/free" )
{
	$("#master").css( 'background', 'none' );
	$("#master").css( 'border', 'none' );
}
$("#master").show();

//	admin page
$('body').click(function(e) {

	//log( e.target.id );
	
	if( e.target.id != "icp_collection_nav_color" && e.target.id != "" ) $("#iColorPicker").hide();
});

$("#preview_domain").click(function() {

	var valid = true;
    
    if( $("#collection_nav_color").val() == "" ) valid = false;		log( "collection_nav_color: " + $("#font_style").val() );
    if( $("#set_nav_color").val() == "" ) valid = false;			log( "set_nav_color: " + $("#font_style").val() );
    if( $("#background_color").val() == "" ) valid = false;			log( "background_color: " + $("#font_style").val() );
    if( $("#font_color").val() == "" ) valid = false;				log( "font_color: " + $("#font_style").val() );
    if( $("#font_style").html() == "" ) valid = false;				log( "font_style: " + $("#font_style").html() );
    if( $("#flickr_username").val() == "" ) valid = false;			log( "flickr_username: " + $("#flickr_username").val() );

	if( valid )
    {
	    if( $("#domain").val() != "" )
	    {
	    	window.open( "http://"+$("#domain").val(), '_blank');
	    }
	    else
	    {
	    	window.open( "http://flickfolia.com/"+$("#first_name").val()+"-"+$("#last_name").val(), '_blank');
	    }
	}
	else
	{
		$('.error').html( 'Please fill in all required fields under site information.' );
	}
	
	    
    return false;
});

$("#submit_billing_info").click(function() {
    
    // validate
    var valid = true;
    
    if( $("#first_name").val() == "" ) valid = false;
    if( $("#last_name").val() == "" ) valid = false;
    if( $("#email").val() == "" ) valid = false;
    if( $("#cc_number").val() == "" ) valid = false;
    if( $("#cc_month").val() == "" ) valid = false;
    if( $("#cc_year").val() == "" ) valid = false;
    if( $("#cc_cvv").val() == "" ) valid = false;
    
    $('.error').html( '<img src="https://flickfolia.com/images/ajax-loader.gif" width="30">' );
    
    if( valid )
    {
	    $.post("/admin/submit_billing_info/",
	    {
	    	first_name : $("#first_name").val(),
	    	last_name : $("#last_name").val(),
	    	email : $("#email").val(),
	    	cc_number: $('#cc_number').val(),
            cc_exp_month: $('#cc_month option:selected').val(),
            cc_exp_year: $('#cc_year option:selected').val(),
            cc_card_type: $('#card_type option:selected').val(),
            cc_cvv: $('#cc_cvv').val()
	    
	    },
		function( data )
		{
			data = jQuery.parseJSON( data );
			//log( "data: " + data );
			$('.error').html( data.message );
		});
	}
    else
    {
    	// return an error
    	$('.error').html( 'Please fill in all required fields.' );
    }

    return false;
});

$("#submit_site_info").click(function() {
    
     // validate
    var valid = true;
    
    $('.error').html( '<img src="https://flickfolia.com/images/ajax-loader.gif" width="30">' );
    
    if( $("#collection_nav_color").val() == "" ) valid = false;		log( "collection_nav_color: " + $("#font_style").val() );
    if( $("#set_nav_color").val() == "" ) valid = false;			log( "set_nav_color: " + $("#font_style").val() );
    if( $("#background_color").val() == "" ) valid = false;			log( "background_color: " + $("#font_style").val() );
    if( $("#font_color").val() == "" ) valid = false;				log( "font_color: " + $("#font_style").val() );
    if( $("#font_style").html() == "" ) valid = false;				log( "font_style: " + $("#font_style").html() );
    if( $("#flickr_username").val() == "" ) valid = false;			log( "flickr_username: " + $("#flickr_username").val() );
    
    //log( "embiggen: " + $("#embiggen:checked").val() )
    
    if( valid )
    {
    
    	if( $("#domain").val() == "" ) domain = "http://flickfolia.com/"+$("#first_name").val()+"-"+$("#last_name").val();
		else domain = $("#domain").val();
    
    	$.post("/admin/submit_site_info/",
	    {
	    	collection_nav_color : $("#collection_nav_color").val(),
	    	set_nav_color : $("#set_nav_color").val(),
	    	background_color : $("#background_color").val(),
	    	font_color : $("#font_color").val(),
	    	font_style : $("#font_style").html(),
	    	flickr_username : $("#flickr_username").val(),
	    	twitter_username : $("#twitter_username").val(),
	    	facebook_username : $("#facebook_username").val(),
	    	blog_url : $("#blog_url").val(),
	    	embiggen : $("#embiggen:checked").val(),
	    	google_analytics : $("#google_analytics").val(),
	    	domain : $("#domain").val()
	    
	    },
		function( data )
		{
			//data = jQuery.parseJSON( data );
			//log( data );
			
			if( domain.indexOf( 'http://' ) == -1 ) domain = "http://"+domain;
			
			$('.error').html( 'Your <a href="'+domain+'" target="_blank">flickfolia site</a> has been updated.' );
		});
    }
    else
    {
    	// return an error
    	$('.error').html( 'Please fill in all required fields.' );
    }
    

    return false;
});

if( $("#upload_button").is('*') )
{
	// logo upload
	var num_files_uploaded = 0;
	var num_files_submitted = 0;
	
	var uploader = new qq.FileUploader({
	    // pass the dom node (ex. $(selector)[0] for jQuery users)
	    element: document.getElementById('upload_button'),
	    // path to server-side upload script
	    action: '/js/phpupload.php',
	    // additional data to send, name-value pairs
		params: {
		},
		// ex. ['jpg', 'jpeg', 'png', 'gif'] or []
		allowedExtensions: [],        
		// size limit in bytes, 0 - no limit
		// this option isn't supported in all browsers
		sizeLimit: 0,
		onSubmit: function(id, fileName){
			//log( 'submitted' );
			$('.qq-upload-list').show();
			$('.qq-upload-list').css( 'height', '30px' );
			$('.qq-upload-list').html( '<img src="https://flickfolia.com/images/ajax-loader.gif" width="20">' );
			num_files_submitted++;
		},
		onComplete: function( id, fileName, responseJSON )
		{
			log( "fileName: " + fileName );
			log( "responseJSON: " + jQuery.parseJSON( responseJSON ) );
		
			var good = true;
			var error_msg = "";
			for (var key in responseJSON) {
			   var obj = responseJSON[key];
			   for (var prop in obj) {
			      log(prop + " = " + obj[prop]);
			      if( prop == "error" )
			      {
			      	error_msg = obj[prop];
			      	good = false;
			      	num_files_submitted--;
			      	break;
			      }
			      
			      if( prop == "filename" ) final_filename = obj[prop];
			   }
			}
			
			if( good )
			{
			
				$.post("/admin/upload_logo", { file_name: final_filename },
				function( data )
				{
					$('.qq-upload-list').html( 'success: ' + fileName );
					$('#admin_logo').html( '<img src="https://flickfolia.com/images/logos/'+final_filename+'">' );
					
				});
			}
			else
			{
				log( error_msg );
				$('.qq-upload-list').html( error_msg );
			}
		},
		messages: {
		    // error messages, see fileuploader.js for details
		},
		showMessage: function(message){
		   // log(message);
		    //$( '#add' ).append( message );
		}
	});

}

//	facebook
window.fbAsyncInit = function() {
	FB.init({appId: '227492273929565', status: true, cookie: true, xfbml: true});

    /* All the events registered */
    FB.Event.subscribe('auth.login', function(response) {
		// do something with response
        //login();
	});

    FB.Event.subscribe('auth.logout', function(response) {
    // do something with response
        logout();
  	});
};

(function() {
    var e = document.createElement('script');
    e.type = 'text/javascript';
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
      e.async = true;
    document.getElementById('fb-root').appendChild(e);
 	}());

function login(){
	document.location.href = "/admin/login";
}

function logout(){
	document.location.href = "/admin/logout";
}


// twitter
(function($){ 		  
	$.fn.popupWindow = function(instanceSettings){
		
		return this.each(function(){
		
		//$(this).click(function(){
		
		$.fn.popupWindow.defaultSettings = {
			centerBrowser:1, // center window over browser window? {1 (YES) or 0 (NO)}. overrides top and left
			centerScreen:1, // center window over entire screen? {1 (YES) or 0 (NO)}. overrides top and left
			height:600, // sets the height in pixels of the window.
			left:0, // left position when the window appears.
			location:0, // determines whether the address bar is displayed {1 (YES) or 0 (NO)}.
			menubar:0, // determines whether the menu bar is displayed {1 (YES) or 0 (NO)}.
			resizable:0, // whether the window can be resized {1 (YES) or 0 (NO)}. Can also be overloaded using resizable.
			scrollbars:0, // determines whether scrollbars appear on the window {1 (YES) or 0 (NO)}.
			status:0, // whether a status line appears at the bottom of the window {1 (YES) or 0 (NO)}.
			width:700, // sets the width in pixels of the window.
			windowName:null, // name of window set from the name attribute of the element that invokes the click
			windowURL:null, // url used for the popup
			top:0, // top position when the window appears.
			toolbar:0 // determines whether a toolbar (includes the forward and back buttons) is displayed {1 (YES) or 0 (NO)}.
		};
		
		settings = $.extend({}, $.fn.popupWindow.defaultSettings, instanceSettings || {});
		
		var windowFeatures =    'height=' + settings.height +
								',width=' + settings.width +
								',toolbar=' + settings.toolbar +
								',scrollbars=' + settings.scrollbars +
								',status=' + settings.status + 
								',resizable=' + settings.resizable +
								',location=' + settings.location +
								',menuBar=' + settings.menubar;

				settings.windowName = this.name || settings.windowName;
				settings.windowURL = this.href || settings.windowURL;
				var centeredY,centeredX;
			
				if(settings.centerBrowser){
						
					if ($.browser.msie) {//hacked together for IE browsers
						centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
						centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
					}else{
						centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
						centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
					}
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else if(settings.centerScreen){
					centeredY = (screen.height - settings.height)/2;
					centeredX = (screen.width - settings.width)/2;
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + centeredX +',top=' + centeredY).focus();
				}else{
					window.open(settings.windowURL, settings.windowName, windowFeatures+',left=' + settings.left +',top=' + settings.top).focus();	
				}
				return false;
			});
			
		//});	
	};
})(jQuery);

$('#login_twitter').click( function () {
	$(this).popupWindow({ 
		centerScreen: 1,
		windowURL: "/admin/check_oauth",
	});
	
	//$('#sign_in').html( "<img src='https://flickfolia.com/images/ajax-loader.gif' width='30'>" );
});

if( url.indexOf("https") == -1 )
{
twttr.anywhere
(
	function (T)
	{
		T.hovercards({ expanded: true });
		T(".avatar>img").hovercards({
	      username: function(node) {
	        return node.alt;
	      },
	      expanded: true
	    });
	}
)
}



// fetch tweets for comments on a page
function fetchTweets( query )
{	
	
	// for testing
	//query = "http://sellsimp.ly/k6";
	
	$.ajax(
	{ 
		url: "http://search.twitter.com/search.json", 
		dataType: "jsonp",
		data: 
		{ 
			q: query,
			rpp: 100,
			result_type: "recent"
		}, 
		success: function(data, textStatus, XMLHttpRequest)
		{
			var t = data.results.length;
			var result = {};
			var text = "";
			var username = "";
			var tweetid = "";
			var twitteruserid = "";
			var tweets = "";
			
			if ( t > 0 )
			{
				for ( var i = 0; i < t; i++ )
				{
					result = data.results[ i ];
					
					username = result.from_user;
					tweettext = result.text;
					tweetid = result.id_str;
					twitteruserid = result.from_user_id_str;
					
					/*
					log( "username: " + username );
					log( "tweettext: " + tweettext );
					log( "location: " + location );
					log( "etsyUrl: " + etsyUrl );
					*/
					/*
var index1 = tweettext.indexOf( "http" );
		        	var index2 = tweettext.indexOf( " " , index1 );
		        	var link = tweettext.substr( index1, index2-index1 );
		        	
		        	tweettext = tweettext.replace( tweettext.substr( index1, index2-index1 ), "<a href='" + link + "' target='_blank'>" + link + "</a>" );
*/
					
					tweets += "@" + username + ": &#8220;" + tweettext + "&#8221;<br /><br />";		
				}
				
				//log( tweets );
				
				$("#tweets").html( tweets );
			}
			else
			{
				//log( "No results for " + query + ", try another tag." );
			}
		}
	});
}
//fetchTweets( "#roofusroofijjjj" );

$('#content').show();

