var API_URL = "http:\/\/api2.smartweeter.com";
var SITE_URL = "http:\/\/www.smartweeter.com";
var variation_suggestions = ["Explore all about <tag>, <tag> <url> with extensive information","Find out more details on <tag>, <tag>, <tag> <url>"];

var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
var olderBowser;
var fan_strict_mode = document.compatMode == 'CSS1Compat'; // as oposite to quircks
var main_page_width = 750;
var temp_queue_displayed = false;
var temp_queue_container = false;
var temp_queue_item_container = false;
var wizard_displayed = false;
var page_requires_login = false;
var free_limit = 2;
var after_login_redirect = false;
var header_username = 'false';
var refreshOnQueueRemove = false;

if(typeof(logged_in)!='boolean'){
	var logged_in = null;
}

$(
function(){
	checkFrame();
	applyFrame();
	
	check_login();
	var temp = get_cookie('after_login_redirect');
	if(is_url(temp)){
		after_login_redirect = temp;
	}
	
	// user menu position
	var body_width = $(document.body).width();
	var menu_pos = (body_width-main_page_width)/2;
	$('#member_menu').css('right', menu_pos);
	header_username = document.getElementById('header_username');
}
);

var isFrame = get_cookie('isFrame')==1;
var wasFrame = isFrame;
function checkFrame(){
	isFrame = window.top!==window;
	set_cookie('isFrame', isFrame?1:0, 0, '/');
}

function applyFrame(){
	if(isFrame){
		loadCss(SITE_URL+'/css/frame.css');
	}
	else if(wasFrame){
		loadCss(SITE_URL+'/css/undoFrame.css');
		$('.FH').show();
	}
}

function loadCss(URL){
	var link = $("<link>");
	link.attr({
		type: 'text/css',
		rel: 'stylesheet',
		href: URL
	});
	$("head").append( link ); 
}

applyFrame();

function set_active_tab(tab_group_class, active_tab_id, clicked_tab){
	$('.'+tab_group_class).css('display','none');
	$('#'+active_tab_id).css('display','block');
	$(clicked_tab).siblings().removeClass('selected');
	$(clicked_tab).addClass('selected');
}

function make_service_call(call_params, callback){
	var request_url = API_URL+'/index.php?output=jquery&callback=?';
	
	jQuery.ajax({
		type: "GET",
		url: request_url,
		data: call_params,
		success: callback,
		dataType: 'json'
	});
}

function verify_given_url(url){
        if(is_url(url, true)){
		url = 'http://'+url;
	}
	if(is_url(url)){
		return true;
	}else{
		alert('Please enter your website URL');
		return false;
	}
}


function get_url_tweets(url, type, links_plh_id){
	if (verify_given_url(url)){
            if(is_url(url, true)){
		url = 'http://'+url;
            }
            links_plh = document.getElementById(links_plh_id);
            links_plh.innerHTML = '';

            var wait_img = document.createElement('img');
            wait_img.src = SITE_URL+'/images/loading1.gif';
            wait_img.style.margin = '40px';
            links_plh.appendChild(wait_img);

            var call_params = {
                    what:'spider',
                    url:url,
                    type:(type=='xml_sitemap'?type:'level1scan'),
                    title_only:(type=='level2scan'?'n':'y')
            };

            make_service_call(call_params, function(data){display_url_tweets(data, links_plh, type)});
        }
}

function set_cookie(name,value,expires,path,domain,secure) {
	if(typeof(expires)!='number'){
		expires = 315360000000; // 10 years
	}
	
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	if(!domain){
		var temp = window.location.href.match(/https?:\/\/.*?([a-z0-9\-_]+\.[a-z]{2,4})(:[0-9]+)?(\/.*)?$/);
		domain = temp[1];
	}
	
    var cookieString = name + "=" +escape(value) + 
       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
       ( (path) ? ";path=" + path : "") + 
       ( (domain) ? ";domain=" + domain : "") + 
       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

function get_cookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}

function delete_cookie(name, path, domain) {
	if (get_cookie(name)){
		document.cookie = name + "=" +
		((path)?";path="+path:"") +
		((domain)?";domain="+domain:"") +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}

function display_url_tweets(data, links_plh, type){
	links_plh.innerHTML = '';
	
	if(typeof(data)=='object'){
		if(typeof(data.successfull)=='boolean' && data.successfull && typeof(data.links)=='object'){
			if(data.links.length>0){
				var links_container = document.createElement('div');
				links_container.className = 'links_container';
				
				if(type=='level1scan'){
					for(var i in data.links){
						new Status.from_link(data.links[i], links_container)
					}
				}
				else{
					load_links_async(data.links, links_plh, links_container);
				}
			
				links_plh.appendChild(links_container);
			}
			else{
				links_plh.innerHTML = 'No webpage found';
			}
		}
		else{
			var error_text = 'An error occured while fetching the URL';
			if(typeof(data.error)=='string' && data.error){
				error_text = data.error;
			}
			alert(error_text);
		}
	}
}

var stop_async_loading = Array();
var active_async_loading = Array();
var link_items_per_page = 15;
var link_loading_animation = false;
function load_links_async(links, links_plh, links_container, link_index, link_data, link_set_id, load_up_to){
	if(typeof(link_index)!='number'){
		link_index = 1;
		stop_async_loading[links_plh.id] = false;
	}
	if(typeof(link_set_id)!='number'){
		link_set_id = Math.random();
		active_async_loading[links_plh.id] = link_set_id;
	}
	if(typeof(load_up_to)!='number'){
		load_up_to = link_items_per_page;
	}
	
	if(typeof(link_loading_animation)!='object'){
		link_loading_animation = document.createElement('div');
		
		var loading_img = document.createElement('img');
		loading_img.src = SITE_URL+'/images/loading_16.gif';
		loading_img.align = 'absmiddle';
		link_loading_animation.appendChild(loading_img);
		
		var pre_text = document.createElement('span');
		pre_text.innerHTML = '&nbsp;Loading';
		link_loading_animation.appendChild(pre_text);
		
		jQuery(links_plh).after(link_loading_animation);
	}
	
	if(active_async_loading[links_plh.id]!=link_set_id){
		return;
	}
	
	var temp_id = links_plh.id.substr(0, links_plh.id.indexOf('_links_plh'))+'_progress';
	var progress_plh = document.getElementById(temp_id);
	
	if(typeof(link_data)=='object'){
		if(typeof(link_data.links)=='object' && link_data.links.length>0){
			new Status.from_link(link_data.links[0], links_container);
		}
		link_index++;
	}
	
	progress_plh.innerHTML = 'Showing '+(link_index-1)+' of '+links.length;
	
	if(link_index>load_up_to){
		link_loading_animation.style.display = 'none';
		
		if(link_index<=links.length){
			var morePlh = document.createElement('div');
			morePlh.align = 'center';
			morePlh.style.margin = '10px 0';
			
			var moreBtn = document.createElement('input');
			moreBtn.type = 'button';
			moreBtn.value = 'More';
			moreBtn.onclick = function(){
				links_container.removeChild(morePlh);
				load_links_async(links, links_plh, links_container, link_index, false, link_set_id, load_up_to+link_items_per_page);
			}
			morePlh.appendChild(moreBtn);
			jQuery(moreBtn).button();
		
			links_container.appendChild(morePlh);
		}
	}
	else if((typeof(stop_async_loading[links_plh.id])!='boolean' || !stop_async_loading[links_plh.id]) && link_index<=links.length){
		link_loading_animation.style.display = 'block';
		
		var stop_btn = document.createElement('a');
		stop_btn.title = 'stop';
		stop_btn.innerHTML = 'stop';
		stop_btn.className = 'load_links_async_stop';
		stop_btn.onclick = function(){
			stop_async_loading[links_plh.id] = true;
		}
		progress_plh.appendChild(stop_btn);
		
		var call_params = {
			what:'spider',
			url:links[link_index-1].href,
			type:'level0scan'
		};
		
		var temp_callback = function(data){
			load_links_async(links, links_plh, links_container, link_index, data, link_set_id, load_up_to);
		}
		
		make_service_call(call_params, temp_callback);
	}
	else{
		link_loading_animation.style.display = 'none';
	}
}

function remove_from_temp_queue(index2remove){
	var call_params = {
		what:'account',
		op:'remove_from_temp_queue',
		index2remove:index2remove
	};
	make_service_call(call_params, remove_from_temp_queue_callback);
}

function remove_from_temp_queue_callback(data){
	if(typeof(data)=='object' && typeof(data.successfull)=='boolean' && data.successfull){
		temp_queue = data.temp_queue;

		$('#active_count_st').html(temp_queue.length);
		if (temp_queue.length < 1){
			$('#active_wizard_st').hide();
		}

		$('#temp_queue_count').html(temp_queue.length);
		
		if(refreshOnQueueRemove){
			window.location.href = window.location.href;
		}
		
		refresh_temp_queue_display();
	}
}

var onEnterCallbacks = Array();
function onEnter(element, callback){
	if(typeof(element)=='object' && typeof(callback)=='function'){
		var callback_key = element.id+'_'+Math.random();
		var temp = function(e){
			var keynum = null;
			if(e.keyCode){ // IE
				keynum = e.keyCode
			}
			else if(e.which){ // Netscape/Firefox/Opera
				keynum = e.which;
			}
			
			if(keynum==13){ //enter
				callback();
			}
		}
		onEnterCallbacks[callback_key] = temp;
		
		element.setAttribute('onkeypress', 'onEnterCallbacks["'+callback_key+'"](event)');
	}
}

function free_limit_alert(){
	if(logged_in){
		return;
	}
	
	var alert_text = 'Notice: Up to two Free SmarTweets may be created. Please login or register<br />to purchase the right plan to use powerful features of our system.';
	var btn_options = {ok:'OK',login:'Login / Register'};
	var callback = function(opt){
		if(opt=='login'){
			authenticate();
		}
	};
	var confirm_window = fan_window.confirm(alert_text, btn_options, callback);
	$(confirm_window.get_window_element()).find('input[type=button]').button();
}


function is_url(string, without_protocol){
	if(typeof(string)!='string'){
		return false;
	}
	
	if(typeof(without_protocol)!='boolean'){
		without_protocol = false;
	}
	
	var regexpStr = "^";
	
	// protocol
	if (!without_protocol) {
		regexpStr += "https?:\\/\\/";
	}
	
	// domain
	if (typeof(sandbox_mode)=='boolean' && sandbox_mode){
		regexpStr += "([a-z0-9_\\-\\.]+)";
	}
	else {
		regexpStr += "([a-z0-9_\\-]+\\.)+[a-z]{2,4}";
	}
	
	regexpStr += "(\\/[^\\s]*)?"; // URI
	regexpStr += "$";
	
	regexp = new RegExp(regexpStr, 'i');
	
	return string.match(regexp);
}

function shorten_url(url, callback){
	display_live_edit();
	var shorte_url_request = 'http://avoo.net/index.php?op=convert&url=' + encodeURIComponent(url) + '&to=true&output=jquery&callback=?';

	jQuery.getJSON(shorte_url_request,callback);
}

function save_publish_details(callback, preserveStep){
	var publish_date = $('input[name=date]').val();
	var date_until_rand = $('input[name=date_until_rand]').val();
	var campaign = $('input[name=campaign]').val();
	var camp_id = $('#camp_id_select').val();
	var posts = Number($('input[name=posts]').val());
	var auth_opts = document.getElementById('auth_id_input').childNodes;
	var multiple_postings = document.getElementById('multiple_postings_input').checked;
	var best_suited = document.getElementById('best_suited_input').checked;
	var foreign_accounts = document.getElementById('foreign_accounts_input').checked;
	
	if(foreign_accounts && !confirm('You will be charged for any message posted using a third party account.\nContinue?')){
		return;
	}
	
	var call_params = {
		what:'account',
		op:'set_temp_queue_publish_time',
		publish_date:publish_date,
		date_until_rand:date_until_rand,
		campaign:campaign,
		camp_id:camp_id,
		posts:posts,
		multiple_postings:(multiple_postings?'y':'n'),
		best_suited:(best_suited?'y':'n'),
		foreign_accounts:(foreign_accounts?'y':'n')
	};
	
	for(var i in auth_opts){
		if(auth_opts[i].selected){
			call_params['auth_id['+i+']'] = auth_opts[i].value;
		}
	}
	
	var tmpCallback = function(data){
		save_publish_details_callback(data, callback, preserveStep);
	}
	
	make_service_call(call_params, tmpCallback);
}

function save_publish_details_callback(data, callback, preserveStep){
	if(typeof(data)=='object' && typeof(data.successfull)=='boolean' && data.successfull){
		publish_time_is_set = true;
		
		if(typeof(callback)=='function'){
			callback(data);
		}
	}
	else{
		if(!preserveStep){
			go_to_step('publish_date_select');
		}
		publish_time_is_set = false;
		
		if(typeof(data.error)=='string' && data.error){
			error_message(data.error);
		}
	}
}


// add
function makeArray() {
for (i = 0; i<makeArray.arguments.length; i++)
this[i + 1] = makeArray.arguments[i];
}

function my_display(my_date){
	var months = new makeArray('January','February','March','April','May',
	'June','July','August','September','October','November','December');
	var date = new Date(my_date);
	var day = date.getDate();
	var month = date.getMonth() + 1;
	var yy = date.getYear();
	var year = (yy < 1000) ? yy + 1900 : yy;
	var my_publish_date = months[month] + " " + day + " " + year;	
	return my_publish_date;
}
//end add

var datepicker = false;
function show_datepicker(input_elem, placeholder_selector){
	if(!placeholder_selector){
		placeholder_selector = '#datepicker';
	}
	
	var min_date = new Date();
	datepicker = $(placeholder_selector).datepicker({onSelect: function(dateText, inst) {datepicker_select(dateText, inst, input_elem, placeholder_selector)}, dateFormat: 'mm/dd/yy', minDate:min_date});
	var matches = input_elem.value.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/)
	if(input_elem.value && matches){
		var selected_date = new Date(matches[3],matches[1]-1,matches[2]); 
		datepicker = $(placeholder_selector).datepicker('setDate', selected_date);
	}
}

function datepicker_select(dateText, inst, input_elem, placeholder_selector){
	input_elem.value = dateText;
	
	$(placeholder_selector).datepicker('destroy');
}

function recurrence_change(recurance_select){
	var recurrence_val = $(recurance_select).val();
	if(recurrence_val){
		$('.repeat_until').css('display', 'block');
	}
	else{
		$('.repeat_until').css('display', 'none');
	}
	
	if(recurrence_val=='custom'){
		$('.custom_repeat').css('display', 'block');
	}
	else{
		$('.custom_repeat').css('display', 'none');
	}
}

function go_to_step(step){
	if(!wizard_displayed){
		// go to wizard
		var temp_url = SITE_URL;
		temp_url = set_url_param('step', step, temp_url);
		window.location.href = temp_url;
		return;
	}
	
	set_active_tab('step_container', step);
	$('#'+step+'_radio').attr('checked', 'checked');
//	var radio_input = document.getElementById();
//	radio_input.checked = true;
//	$("#steps").buttonset('refresh');
	refresh_steps();
}

function refresh_active_steps(){
	if(temp_queue.length>0){ // step 2 active
		$('.step2_link').attr('disabled', false);
		show_steps_container();
	}
	else{
		$('.step2_link').attr('disabled', true);
	}
	
	if(publish_time_is_set){
		$('.step3_link').attr('disabled', false);
	}
	else{
		$('.step3_link').attr('disabled', true);
	}
	
	if(logged_in && publish_time_is_set){
		$('.finish_link').attr('disabled', false);
	}
	else{
		$('.finish_link').attr('disabled', true);
	}
	
	refresh_steps();
	$("button").button('refresh');
	
	setTimeout(refresh_active_steps, 200);
}

function set_url_param($param, $value, $link, $unset){
	if (!$link){
		$link = window.location.href;
	}
	
	var patern = new RegExp("([\&\?])"+$param+"=[^\&]*(\&|$)");
	$link = $link.replace(patern, "$1");
	$last_char = $link.substr($link.length-1);
	
	if (!$unset){
		if ($last_char!='&' && $last_char!='?'){
			if ($link.indexOf('?')!=-1){
				$link += '&';
			}
			else {
				$link += '?';
			}
		}
		$link += $param+"="+encodeURIComponent($value);
	}
	
	return $link;
}

function temp2queue(callback, extraParams){
	var is_public = false;
	var tmp = document.getElementById('is_public_input');
	if(tmp && tmp.checked){
		is_public = true;
	}
	
	var call_params = {
		what:'account',
		op:'temp2queue',
		is_public:is_public?'y':'n'
	};
	
	if(typeof(extraParams)=='object'){
		for(var i in extraParams){
			if(typeof(extraParams[i])=='string' || typeof(extraParams[i])=='number'){
				call_params[i] = extraParams[i];
			}
		}
	}
	
	var temp_callback = function(data){
		if(typeof(callback)=='function'){
			callback(data);
		}
		temp2queue_callback(data);
	}
	
	make_service_call(call_params, temp_callback);
}

function togglePostNoDIsplay(cbxElem, toggleClass){
	if(cbxElem.checked){
		$('.'+toggleClass).show();
	}
	else{
		$('.'+toggleClass).hide();
	}
}

function temp2queue_callback(data){
	if(typeof(data)=='object'){
		var info_text = '';
		
		if(typeof(data.added)=='object' && data.added.length>0){
			info_text += data.added.length+' smarTweets saved';
		}
		
		if(typeof(data.failed)=='object' && data.failed.length>0){
			info_text += (info_text?'<br />':'')+data.failed.length+' smarTweets failed saving';
			temp_queue = data.failed;
		}
		else{
			temp_queue = Array();
		}
		
		if(!info_text){
			info_text = 'No smarTweet saved';
		}
		
		if(typeof(data.error)=='string' && data.error){
			alert(data.error);
		}
		
		info_message(info_text, 6);
		
		publish_time_is_set = data.publish_time_is_set;
		$('#temp_queue_count').html(temp_queue.length);
		$('#queue_count').html(data.queue_count);
	}
	else{
		alert('An error occured while saving your queue');
		return;
	}
}

function wizard_temp2queue_callback(data){
	if(typeof(data.failed)=='object' && data.failed.length==0){
		setTimeout(function(){window.location.href = SITE_URL+'/queue'}, 4000);
	}
	
	/*if(typeof(data)=='object' && typeof(data.successfull)=='boolean' && data.successfull){
//		go_to_step('pages_tabs');
	}*/
}

function info_message(message, hide_delay, animation_speed){
	display_message(message, 'info_box', hide_delay, animation_speed);
}

function error_message(message, hide_delay, animation_speed){
	display_message(message, 'error_box', hide_delay, animation_speed);
}

function display_message(message, class_name, hide_delay, animation_speed){
	if(typeof(hide_delay)!='number' || hide_delay<1){
		hide_delay = message.length / 10; // 10 characters per seconds
		if(hide_delay<3){
			hide_delay = 3;
		}
	}
	if(typeof(animation_speed)!='number'){
		animation_speed = 500;
	}
	
	// convert to miliseconds
	hide_delay = hide_delay * 1000;
	
	// nl2br
	message = message.replace(/\n/g, '<br />');
	
	var info_div = document.createElement('div');
	info_div.className = class_name;
	info_div.innerHTML = message;
	info_div.style.display = 'none';
	document.body.appendChild(info_div);
	$(info_div).show('blind',animation_speed);
	
	setTimeout(function(){$(info_div).hide('blind',animation_speed)}, hide_delay);
}

function refresh_steps(){
	var step_inputs = $('#steps > :radio').get();
	
	for(i in step_inputs){
		var step_input_details = step_inputs[i];
		
		var class_name = step_input_details.id;
		if(step_input_details.checked){
			class_name = step_input_details.id+'_checked';
		}
		if(step_input_details.disabled){
			class_name = step_input_details.id+'_disabled';
		}
		
		var label = $('label[for='+step_input_details.id+']').get(0);
		if(ie4 && typeof(label.onclick)!='function'){
			label.onclick = function(){
//				trim radio from for
				var step = this.getAttribute('for');
				step = step.substr(0, step.indexOf('_radio'));
				go_to_step(step);
			}
		}
		label.className = class_name;
	}
}

function authenticate(return_url, force_auth, type, reload_opener){
	if(!return_url){
		return_url = window.location.href;
	}
	if(!force_auth){
		force_auth = false;
	}
	
	if(return_url!=window.location.href){
		after_login_redirect = return_url;
	}
	
	if(!type){
		type = 'twitter';
	}
	
	if(logged_in && !force_auth){
		if(return_url!=window.location.href){
			window.location.href = return_url;
		}
	}
	else{
		var frame_src = API_URL+'/index.php?what=account&op=authorize&close_on_finish=y';
		if(reload_opener){
			frame_src += '&reload_opener=y';
		}
		var width = 800;
		var height = 400;
		
		switch (type){
			case 'twitter':
				break;
				
			case 'facebook':
				frame_src += '&type='+type;
				width = 700;
				height = 350;
				break;
				
			case 'buzz':
				frame_src += '&type='+type;
				width = 700;
				height = 425;
				break;
				
			case 'yspan':
				frame_src += '&type='+type;
				width = 700;
				height = 350;
				break;
		}
		var popup_win = centeredPopUp(frame_src, width, height);
	}
}

var fragmentActions = {
	'reload':window.location.reload
};

check_fragment = function(){
	var temp = window.location.href.match(/([^#]+)#(([a-z_]+)=?([^&]*)&?).*$/);
	if(temp){
		var matched = temp[2];
		var param = temp[3];
		var value = temp[4];
		if(typeof(fragmentActions[param])=='function'){
			// remove fragment
			var new_url = window.location.href.replace(matched, '');
			window.location.href = new_url;
			fragmentActions[param](value);
		}
	}
	
	setTimeout(check_fragment, 100);
};

//check_fragment();

function centeredPopUp(theURL, myWidth, myHeight, winName) {
	if(!winName){
		winName = ('win_'+Math.random()).replace('.','');
	}
	var features='toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0';
	var isCenter = 'true';
	if(window.screen)if(isCenter)if(isCenter=="true"){
		var myLeft = (screen.width-myWidth)/2;
		var myTop = (screen.height-myHeight)/2;
		features+=(features!='')?',':'';
		features+=',left='+myLeft+',top='+myTop;
	}
	features += ((features!='')?',':'')+'width='+myWidth+',height='+myHeight;
	
	var handle = window.open(theURL, winName, features);
//	handle.opener = window;
	handle.focus();
	return handle;
}

function setOnLogin(callback){
	if(typeof(callback)=='function'){
		onLoginCallback.push(callback);
	}
}

var onLoginCallback = [];

function requireLogin(){
	if(!logged_in){
		var container = document.createElement('div');
		container.style.padding = '20px';
		
		var infoEl = document.createElement('div');
		container.appendChild(infoEl);
		infoEl.innerHTML = 'In order to continue you must authenticate';
		
		var choseTxt = document.createElement('span');
		container.appendChild(choseTxt);
		choseTxt.innerHTML = 'Choose method: ';
		
		var twBtn = document.createElement('img');
		container.appendChild(twBtn);
		twBtn.className = 'btn';
		twBtn.src = SITE_URL+'/images/icon/32/twitter.png';
		twBtn.onclick = authenticate;
		twBtn.align = 'absmiddle';
		twBtn.style.margin = '5px 10px';
		
		var fbBtn = document.createElement('img');
		container.appendChild(fbBtn);
		fbBtn.className = 'btn';
		fbBtn.src = SITE_URL+'/images/icon/32/facebook.png';
		fbBtn.onclick = function(){authenticate(null, null, 'facebook')};
		fbBtn.align = 'absmiddle';
		fbBtn.style.margin = '5px 10px';
		
		fan_show_transparent_bg();
		var login_window = new fan_window(document.body, 'login', container, {onclose:fan_hide_transparent_bg});
		login_window.center_window();
		setOnLogin(function(){login_window.close();});
		
		return false;
	}
	
	return true;
}

check_login_activa_calls = [];
function check_login(data){
	if(typeof(data)=='object' && data.successfull){
		check_login_activa_calls.pop();
		
		if(logged_in !== data.logged_in){
			if(data.logged_in){
				if(is_url(after_login_redirect)){
					set_cookie('after_login_redirect','',0,'/');
					window.location.href = after_login_redirect;
				}
				else if(typeof(initialLoggedStatus)=='boolean' && !initialLoggedStatus && window.location.href==SITE_URL+'/'){
					window.location.href = SITE_URL+'/account';
				}
				
				if(data.username){
					username = data.username;
				}
				else{
					username = data.name;
				}
				
				var login_info = "You are now logged in as " + username;
				var auth_id_input = document.getElementById('auth_id_input');
				
				$('.require_login').css('display','');
				$('.require_anonymous').css('display','none');
				if(typeof(data.queue_count)=='number'){
					$('#queue_count').html(data.queue_count);
				}
				if(auth_id_input && typeof(data.auths)=='object'){
					auth_id_input.innerHTML = '';
					for(var i in data.auths){
						var temp_opt = document.createElement('option');
						temp_opt.value = data.auths[i].auth_id;
						temp_opt.innerHTML = data.auths[i].type+': '+data.auths[i].username;
						auth_id_input.appendChild(temp_opt);
					}
				}
			}
			else{
				var login_info = 'Please login to continue. <img src="'+SITE_URL+'/images/Sign-in-with-Twitter-lighter.png" onclick="authenticate(set_url_param(\'step\', \'authenticate_plh\'));" align="absmiddle" alt="login with Twitter" height="24" width="151" style="margin-right:10px;" />';
				$('.require_login').css('display','none');
				$('.require_anonymous').css('display','');
			}
			$('#login_status').html(login_info);
			
			logged_in = data.logged_in;
			
			$(header_username).html(username);
			
			if(logged_in){
				var callbacks = onLoginCallback;
				onLoginCallback = [];
				for(var i=0; i<callbacks.length; i++){
					callbacks[i]();
				}
			}
			
			try{
				fan_hide_transparent_bg(); // in case shown by authenticate function
			}
			catch(E){}
		}
		
		if(page_requires_login && !data.logged_in){
			after_login_redirect = window.location.href;
			set_cookie('after_login_redirect',after_login_redirect,0,'/');
			window.location.href = SITE_URL;
		}
	}
	else{
		if(check_login_activa_calls.length==0){
			var parameters = {
				what:'account',
				op:'check_login',
				page_login_state:(logged_in?'y':'n')
			}
			make_service_call(parameters, check_login);
			check_login_activa_calls.push(1);
		}
		
		setTimeout(check_login, 2000);
	}
}

function toggle_temp_queue(){
/*	if(!wizard_displayed){
		// go to wizard
		window.location.href = SITE_URL;
		return;
	}*/
	
	if(!temp_queue_displayed){
		if(!temp_queue_container){
			var member_menu = document.getElementById('member_menu');
			temp_queue_container = document.createElement('div');
		
			temp_queue_container.id = 'temp_queue_container';
			temp_queue_container.className = 'pop_over_box';
		
			//position
			var body_width = $(document.body).width();
			var pos = (body_width-main_page_width)/2;
			$(temp_queue_container).css('right', pos);
			
			// header
			var top_container = document.createElement('div');
			top_container.className = 'temp_queue_top_container';
			temp_queue_container.appendChild(top_container);
			
			var close_btn = document.createElement('a');
			close_btn.innerHTML = 'close';
			close_btn.onclick = toggle_temp_queue;
			top_container.appendChild(close_btn);
			
			//body
			temp_queue_item_container = document.createElement('div');
			temp_queue_item_container.id = 'temp_queue_item_container';
			temp_queue_container.appendChild(temp_queue_item_container);
			
			//footer
			var footer = document.createElement('div');
			footer.id = 'temp_queue_footer';
			temp_queue_container.appendChild(footer);
			
			member_menu.appendChild(temp_queue_container);
/*			
			// continue button
			var continue_btn = document.createElement('button');
			continue_btn.onclick = function(){
				go_to_step('publish_date_select');
				toggle_temp_queue();
			}
			continue_btn.className = "step2_link";
			continue_btn.innerHTML = 'continue';
			footer.appendChild(continue_btn);
			$(continue_btn).button();
*/
			
			// basket link
			var bskLnk = document.createElement('a');
			bskLnk.href = SITE_URL+'/cart';
			bskLnk.innerHTML = 'view basket';
			footer.appendChild(bskLnk);
			$(bskLnk).button();
		}
		refresh_temp_queue_display();
		
		$(temp_queue_container).show('blind', 500);
		temp_queue_displayed = true;
	}
	else{
		$(temp_queue_container).hide('blind', 500);
		temp_queue_displayed = false;
	}
}

function add2temp_queue_display(status_text, index){
	if(temp_queue_container){
		var item_container = document.createElement('div');
		item_container.className = 'temp_queue_item';
		
		var text_elem = document.createElement('div');
		text_elem.innerHTML = status_text;
		item_container.appendChild(text_elem);
		
		var btn_plh = document.createElement('div');
		btn_plh.className = 'temp_queue_item_btn_plh';
		item_container.appendChild(btn_plh);
		
		var remove_btn = document.createElement('a');
		remove_btn.className = 'temp_queue_remove_btn';
		remove_btn.title = 'remove';
		remove_btn.onclick = function(){
			if(confirm('Remove?')){
				remove_from_temp_queue(index);
			}
		}
		btn_plh.appendChild(remove_btn);
		
		temp_queue_item_container.appendChild(item_container);
	}
}

function refresh_temp_queue_display(){
	temp_queue_item_container.innerHTML = '';
	
	for(i in temp_queue){
		add2temp_queue_display(temp_queue[i], i);
	}
}

function logout(){
	var parameters = {
		what:'account',
		op:'logout'
	}
	make_service_call(parameters);
}

function remove_from_queue(entry_id, item_container, skip_confirmation){
	if(typeof(skip_confirmation)!='boolean' || !skip_confirmation){
		if(!confirm('Remove from queue')){
			return;
		}
	}
	
	var parameters = {
		what:'post',
		op:'remove_from_queue',
		entry_id:entry_id
	}
	
	make_service_call(parameters, function(data){remove_from_queue_callback(data, item_container)});
}

function remove_from_queue_callback(data, item_container){
	if(typeof(data)=='object' && typeof(data.successfull)=='boolean' && data.successfull){
		$(item_container).hide('blind', 500);
		$('#queue_count').html(data.queue_count);
	}
}

function copy2clipboard(inElement) {
	if (inElement.createTextRange) {
		var range = inElement.createTextRange();
		if (range)
			range.execCommand('Copy');
	}
	else {
		inElement.select();
		var flashcopier = 'flashcopier';
		if(!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="'+SITE_URL+'/flash/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}



function fieldTempValue(fieldElem, caption, restore){
	if(restore){
		if(!fieldElem.value){
			fieldElem.value = caption;
		}
	}
	else{
		if(fieldElem.value == caption){
			fieldElem.value = '';
		}
	}
}

function setFieldTempValue(fieldElem, caption, set_now){
	if(set_now){
		fieldElem.value = caption;
	}
	fieldElem.onfocus = function(){
		fieldTempValue(fieldElem,caption,false);
	}
	fieldElem.onblur = function(){
		fieldTempValue(fieldElem,caption,true);
	}
}


function field_shorten_url(url, target){
	if(!is_url(url)){
		alert('This is not a valid URL');
		return;
	}
	
	fan_show_transparent_bg();
	shorten_url(url, function(data){
		field_shorten_url_callback(data, target);
	});
	display_live_edit();
}

function field_shorten_url_callback(data, target){
	if(is_url(data)){
		target.value = data;
		target.focus();
		target.select();
	}
	fan_hide_transparent_bg();
}


function show_add_or_new_tag(status_id){
	$('#show_new_add_tag_'+status_id).html("Edit tag");
}

function show_new_tag_form(status_id){
	$('#all_tags_'+status_id).hide();
	$('#new_tag_'+status_id).css("display","block");
}

function send_tags(status_id) {
	var call_params = {
		what:'tags',
		tags: $('#form_'+status_id + " > input[name=tags]").val(),
		status_id: status_id
	};
	
	make_service_call(call_params, function(data){
		if(data.error) {
			alert( "Error saving data: " + data.error);
		}else {		
			var obj = jQuery.parseJSON(data.result);
			//alert(obj['tag']);	
			var replace_tags = obj['tag'];
			$('#tweet_tags_'+status_id).html(replace_tags);
			$('#all_tags_'+status_id).show();
			$('#new_tag_'+status_id).hide();
			show_add_or_new_tag(status_id);
		}
	});	
}


function preview_text(){
	var text_textarea = $('#status_input').val();
	var text_long_url = $('#long_url_input').val();
	var text_short_url = $('#short_url_input').val();
	var complete_text = '';
	if ( text_short_url == 'Short URL' || text_short_url == '' ){
			complete_text = text_textarea + " " + text_long_url;
	}else{
			complete_text = text_textarea + " " +text_short_url;		
	}	
	$('#preview_text').val(complete_text).show();
}

function retrieve_link(){
	var text_textarea = $('#status_input').val();
	var text_long_url = $('#long_url_input').val();
	var text_short_url = $('#short_url_input').val();
	var complete_text = '';
	if ( text_short_url == 'Short URL' || text_short_url == '' ){
		complete_text = text_long_url;
	}else{
		complete_text = text_short_url;		
	}
	return complete_text;
}

function retrieve_link_new(){
	var text_long_url = $('#long_url_input').html();
	return text_long_url;
}

function preview_text_new(){
	var text_textarea = $('#status_input').val();
	var text_long_url = $('#long_url_input').html();
	var complete_text = text_textarea + " " +text_long_url;		
	$('#preview_text').val(complete_text).show();
}

function before_send_tweet_form_edit(){
	var text_textarea = $('#status_input').val();
	var text_long_url = $('#long_url_input').val();
	var text_short_url = $('#short_url_input').val();
	var complete_text = '';
	if ( text_short_url == 'Short URL' || text_short_url == '' ){
		complete_text = text_textarea + " " + text_long_url;
	}else{
		complete_text = text_textarea + " " + text_short_url;		
	}
	
	//var complete_text = $("#preview_text").val();
	$('#status_input').val(complete_text);
}

function before_send_tweet_form_new(){
	var text_textarea = $('#status_input').val();
	var text_long_url = $('#long_url_input').html();
	var complete_text = '';
	complete_text = text_textarea + " " + text_long_url;		
	//var complete_text = $("#preview_text").val();
	//alert(complete_text);
	$('#status_input').val(complete_text);
}



function display_live_edit(){
	var word=$('#status_input').val();
	var link = retrieve_link();
	var word_link = word + " " + link;
	$("#preview_text").val(word_link);
	return false;	
}

function display_live_new(){
	var word=$('#status_input').val();
	var link = retrieve_link_new();
	var word_link = word + " " + link;
	$("#preview_text").val(word_link);
	return false;	
}

function contain_url(){
        var string = $("#status_input").val();
	var text_long_url = $('#long_url_input').val();
	var text_short_url = $('#short_url_input').val();
        //alert (text_long_url);
        var ok1 = 0;
        var ok2 = 0;
        if (!is_url(text_long_url,1)){
            ok1 = 1;
        }
        //alert (text_short_url);
        if (!is_url(text_short_url,1)){
            ok2 = 1;
        }
        if ( (ok1 == 1) && (ok2 == 1) ){
            alert('You must provide a valid URL');
            return false;
        }
        //alert('true');
        before_send_tweet_form_edit();
        return true;
}

function delete_auth(auth_id){
	if(confirm('Delete this authentication?')){
		var call_params = {
			what:'account',
			op:'del_auth',
			auth_id:auth_id
		};
		
		make_service_call(call_params, delete_auth_callback);
	}
}

function delete_campaign(camp_id){
	if(confirm('Delete this campaign?')){
		var call_params = {
			what:'campaign',
			op:'delete',
			camp_id:camp_id
		};
		
		make_service_call(call_params, function(data){window.location.href=window.location.href});
	}
}

function delete_auth_callback(data){
	var error = '';
	
	if(typeof(data)=='object'){
		if(data.successfull){
			window.location.href = window.location.href;
		}
		else{
			if(typeof(data.error)=='string'){
				error = data.error;
			}
			else{
				error = 'An error occured!';
			}
		}
	}
	else{
		error = 'An error occured!';
	}
	
	if(error){
		alert(error);
	}
}

//function start_crowling(){
//	var url = start_url_input.value;
//
//	if(is_url(url, true)){
//		url = 'http://'+url;
//	}
//
//	if(is_url(url)){
//		show_steps_container();
//
//		url_input.value = url;
//		get_url_tweets(url, 'level2scan', 'url_search_links_plh');
//	}
//	else{
//		alert('Please enter your website URL');
//	}
//}

function show_steps_container(){
	$('#start_plh').css('display','none');
	$('#steps_container').css('display','block');
}

function load_selected_campaign(){
	
	//posts
	$('#posts_input').val('');
	
	var start_date = new Date();
	var end_date = new Date(start_date.getTime()+604800000);
	
	// auths
	var camp_id = $('#camp_id_select').val();
	$('#auth_id_input option').removeAttr('selected');
	
	if(typeof(campaigns[camp_id])=='object'){
		$('#posts_input').val(campaigns[camp_id].posts);
		start_date.setTime(Number(campaigns[camp_id].start_time)*1000);
		end_date.setTime(Number(campaigns[camp_id].end_time)*1000);
		
		if( typeof(campaigns[camp_id].auth_ids)=='object' && campaigns[camp_id].auth_ids.length>0){
			for(var i=0; i<campaigns[camp_id].auth_ids.length; i++){
				$('#auth_id_input option[value='+campaigns[camp_id].auth_ids[i]+']').attr('selected', 'selected');
			}
		}
	}

	if(camp_id=='new'){
		$('.newCampaign').css('display', '');
	}
	else{
		$('.newCampaign').css('display', 'none');
	}
	
	set_date2field(document.getElementById('date_input'), start_date);
	set_date2field(document.getElementById('end_date_input'), end_date);
}

function set_date2field(field, date){
	var day = ''+date.getDate();
	if(day.length==1){
		day = '0'+day;
	}
	var month = ''+(date.getMonth()+1);
	if(month.length==1){
		month = '0'+month;
	}
	
	field.value = month+'/'+day+'/'+date.getFullYear();
}

function field_value2date(field_value, dayTime){
	var date = false;
	
	var matches = field_value.match(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/);
	if(matches){
		if(!dayTime){
			dayTime = 'now';
		}
		
		date = new Date();
		date.setYear(matches[3]);
		
		var month = parseInt(matches[1], 10)-1;
		var day = parseInt(matches[2], 10);
		
		date.setMonth(month, day);
		
		switch(dayTime){
			case 'start':
				date.setHours(0);
				date.setMinutes(0);
				date.setSeconds(0);
				break;
				
			case 'end':
				date.setHours(23);
				date.setMinutes(59);
				date.setSeconds(59);
				break;
		}
	}
	
	return date;
}

function element_search(search_input, items_container, item_class, searchable_class){
	var _self = this;
	
	var temp_items = jQuery(items_container).find('.'+item_class);
	_self.item_containers = [];
	_self.item_texts = [];
	for(var i=0; i<temp_items.length; i++){
		var tmp_index = _self.item_containers.length;
		
		_self.item_containers[tmp_index] = temp_items.get(i);
		_self.item_texts[tmp_index] = [];
		
		var tmp_texts = jQuery(_self.item_containers[tmp_index]).find('.'+searchable_class);
		for(var j=0; j<tmp_texts.length; j++){
			_self.item_texts[tmp_index].push(tmp_texts.get(j).innerHTML);
		}
	}
	
	_self.refresh = function(){
		var keyword = jQuery.trim(search_input.value);
		var reg_exp = new RegExp(keyword, 'i');
		
		for(var i in _self.item_containers){
			var tmp_item = _self.item_containers[i];
			var tmp_txt = _self.item_texts[i];
			
			var match_keyword = false;
			for(var j in tmp_txt){
				if(tmp_txt[j].match(reg_exp)){
					match_keyword = true;
				}
			}
			
			if(match_keyword){
				jQuery(tmp_item).show();
			}
			else{
				jQuery(tmp_item).hide();
			}
		}
	}
	
	search_input.onkeyup = _self.refresh;
}

/**
 * Gets a random key from an array
 * @param Array array
 * @returns mixed array key
 */
function arrayRand(array){
	var keys = [];
	for(var i in array){
		keys.push(i);
	}
	
	return keys[Math.floor(Math.random()*keys.length)];
}

/**
 * unsets an element from an array
 * @param Array array
 * @param mixed key
 * @returns Array
 */
function arrayUnset(array, key){
	var newArray = [];
	
	for(var i in array){
		if(i!=key && typeof(array[i])!='function'){
			newArray[i] = array[i];
		}
	}
	
	return newArray;
}

function arrayCount(array){
	var total = 0;
	
	for(var i in array){
		if(typeof(array[i])!='function'){
			total ++;
		}
	}
	
	return total;
}
