
/* 
 * Page (document) onload actions
 */
$(document).ready(function() {
	
	// Select list button (STATES)
	$( "#stateselect" )
			.button()
			.click(function(e) {
				positionList(e, 'state');
			})
			.next()
			.button( {
					text: false,
					icons: {
						primary: "ui-icon-triangle-1-s"
					}
			})
			.click(function(e) {
					positionList(e, 'state');
				})
			.parent()
			.buttonset();
	// Select list button (PROJECT TYPES)		
	$( "#typeselect" )
			.button()
			.click(function(e) {
				positionList(e, 'type');
			})
			.next()
			.button( {
					text: false,
					icons: {
						primary: "ui-icon-triangle-1-s"
					}
			})
			.click(function(e) {
					positionList(e, 'type');
				})
			.parent()
			.buttonset();
	
	// collapse lists if open (like in 'normal' select tags)	
	$(document).click(function(){
		checkSelectLists();
	});

});

/*
 *	MAIN DATA FUNCTION
 *
 */
function loadAll()
{
	// State selected?
	if($("#stateselect").attr("rel"))
	{
		getAvvo(); // get top-10/base for selected state
	}
	
	// State & Type selected ?
	if($("#stateselect").attr("rel") && $("#typeselect").attr("rel"))	
	{
		getForm(false);
	}
	
	g_type = $("#typeselect span").text();   // 'remembering' current project type
	g_state = $("#stateselect span").text(); // 'remembering' current state
}

/*
 *  Hide / show forms area
 */
function hideForm(obj)
{
	var formDiv = $("#form_place");
	
	if(formDiv.css("display") == 'none')
	{
		formDiv.slideDown();
		$(obj).addClass("hideminus").removeClass("hideplus").attr("title", "Hide Form(s)");
	}
	else
	{
		formDiv.slideUp();
		$(obj).addClass("hideplus").removeClass("hideminus").attr("title", "Show Form(s)");
	}
	return false;
}

/*
 * Show/hide type/state lists
 *
 * Args: e - event obj, add - state/type 
 */
function positionList(e, add)
{
	e.stopPropagation(); // here the event bubling should stop to prevent the opposite action

	if($("#" + add + "_list").css("display") != 'none'){
		$("#" + add + "_list").hide();
		return false;
	}

	var pos = $( "#" + add + "select" ).position();
	pos.top = pos.top + $( "#" + add + "select" ).height() + 5;
	$("#" + add + "_list").css({"left": pos.left + "px", "top": pos.top + "px"}).show();	
	
}

/*
 * collapse lists if open
 */
function checkSelectLists()
{
	if($("#type_list").css("display") != 'none'){
		$("#type_list").hide();
	}
	if($("#state_list").css("display") != 'none'){
		$("#state_list").hide();
	}
}

/*
 * Geting State list from server
 */
function getStates()
{
	showOverlay(1, 'Loading States List'); // covering screeng with overlay
	
	// request URL
	var reqUrl =  g_zlien_url + "/index.php?module=mechanic&event=get_states_list&jsoncallback=?";
	
	// JSONP request
	jQuery.ajax({
        dataType: 'jsonp',
        async:    false,
        jsonp:    'jsonp_callback',
        url:      reqUrl,
        success: function (data) 
        {
        	showOverlay(0, '');    // removing overlay
        	g_states = data;       // 'remembering' states list to global var
            fillStatesList(data);  // filling states to list
        }
    });
}


/*
 * Show overlay
 *
 * Args: flag - 1(show), 0(hide); msg - message to be shown on the ovelay
 */
function showOverlay(flag, msg)
{
	if(flag == 1)
	{
		var ph = pageHeight();
        var pw = pageWidth();
		$("#overlay").css({"height" : ph + "px", "width" : pw + "px", "top":"0px", "left":"0px"}).show();
		
		// place GIF
		var top = parseInt(windowHeight() / 2) + parseInt(scrollY());
		var left = parseInt(windowWidth() / 2) - parseInt($("#ajax_image").width() / 2);
		$("#ajax_image").css({"top":top+"px", "left":left+"px"}).show();
		
		// insert message
		$("#overlay_msg").html(msg);
		
	}
	else
	{
		$("#overlay").hide();
		$("#ajax_image").hide();
		$("#overlay_msg").html();
	}
}


/*
 * move selected data to button value
 *
 * Args: text - state/type name, value - additional attribute, type - state/type
 */
function forwardInfo(text, value, type)
{
 	
	$("#"+type+"select span").text(text);
	$("#"+type+"select").attr("rel", value);
	
	// !IMPORTANT -- Load all possible data
	loadAll();
}

/*
 * Fill state list with data
 *
 * Args: data - JSON object with states list
 */
function fillStatesList(data)
{
	var res = '<ul class="selectlist">';
	for(var i = 0; i < data.length; i++)
	{
		res += '<li class="selectlist_li" onmouseover="$(this).addClass(\'selectlist_hover\')" onmouseout="$(this).removeClass(\'selectlist_hover\')" onclick="forwardInfo(\'' + data[i].state_name + '\', \'' + data[i].state_short + '\', \'state\')">' + data[i].state_name + '</li>';
	}
	res += '</ul>';
	$("#state_list").html(res);
	
	// Load Example Form
	getForm(true);
}

/*
 * Get from server AVVO Top-10 & Knowledge Base
 */
function getAvvo()
{
	// check if we need to load avvo data (if the state is the same there is no need to make a request)
	if(g_state == $("#stateselect span").text())
	{
		return;
	}
	
	showOverlay(1, 'Loading AVVO base'); // covering screeng with overlay
	
	$("#top10_list").html('<font color="#D0D0D0">Loading AVVO base...</font>');
	$("#base_list").html('<font color="#D0D0D0">Loading AVVO base...</font>');
	
	// request URL
	var reqUrl = g_base_url + '/avvo.php?state=' + escape($("#stateselect").attr("rel")) + '&jsoncallback=?';
	
	$.getJSON(reqUrl, function(data) {
		showOverlay(0, '');
        var myTop10list = eval( '(' + base64_decode(data.top) + ')' ); // filling Top-10 list
        var myKnowledge_base = eval( '(' + base64_decode(data.base) + ')' ); // filling Knowledge Base list
        fillAvvo(myTop10list, myKnowledge_base); // calling AVVO area function
	});

}

/*
 * Taking Forms from zlien.com server
 *
 * Args: example - if true we will get example form (Alabama-Private), 
 * otherwise - server will return a form envisaged by state/type selects
 */
function getForm(example)
{
	if(!example)
	{
		var formDIV = 'form_place'; // main form wrapper
		
		// check if we need to load new form (if the state and type are the same there is no need to make a request)
		if(g_state == $("#stateselect span").text() && g_type == $("#typeselect span").text())
		{
			return;
		}
	
		// having state ID
		for(var i = 0; i < g_states.length; i++)
		{
			if(g_states[i].state_name == $("#stateselect span").text())
			{
				var state_id = g_states[i].state_id;
			}
		}
	
		showOverlay(1, 'Loading FORM'); // covering screeng with overlay
		
		// request URL
		var reqUrl = g_zlien_url + '/index.php?module=mechanic&event=get_form&type=' + escape($("#typeselect span").text()) + '&state_id=' + state_id + '&state=' + escape($("#stateselect span").text()) + '&jsoncallback=?';
	}
	else
	{
		var formDIV = 'form_place_example'; // main example wrapper
		showOverlay(1, 'Loading Example FORM'); // covering screeng with overlay
		
		// example from request URL
		var reqUrl = g_zlien_url + '/index.php?module=mechanic&event=get_form&type=Private&state_id=16&state=Alabama&jsoncallback=?';
	}
	
	// JSONP request
	jQuery.ajax({
        dataType: 'jsonp',
        async:    false,
        jsonp:    'jsonp_callback',
        url:      reqUrl,
        success: function (data) 
        {
        	showOverlay(0, '');
        	var form = base64_decode(data.form);
        	$("#" + formDIV).html(form);
        	if(!example)
        	{
				$("div.hidebutton").show(); // +/- button show
				$("#example_wrapper").remove(); // we don't need example any more
        	}
        	
        }
    });
}

/*
 * Filling AVVO area with Top-10 Attorneys list and Knowlrdge Base 
 *
 * Args: top10list - JSON object (http://www.avvo.com/docs/lawyers_api.html), 
 * knowledge_base - JSON object (http://www.avvo.com/docs/knowledgebase_api.html)
 */
function fillAvvo(top10list, knowledge_base)
{
	// Fill in Top-10 list
	var list_arr = top10list.results;
	var list_str = '<table width="100%"><tbody>';
	var profile = 'profile-url';
	var imageUrl = 'image-url';
	var clientRating = 'avvo-rating';

	if(list_arr.length > 0)
	{
		for(var i = 0; i < list_arr.length; i++)
		{
			list_str += '<tr>';
			list_str += '<td style="vertical-align: top;"><img style="width:3em; height:4em;" src="' + list_arr[i][imageUrl] + '" /><div style="font-size:8px;">Rating: ' + list_arr[i][clientRating] + '</div></td>'
			list_str += '<td style="vertical-align: top;">' + '<b>' + list_arr[i].name + '</b>, ' + list_arr[i].address + ', ' + list_arr[i].phone + ', ' + '<a href="' + list_arr[i][profile] + '" target="_blank">more</a></td>';
			list_str += '</tr>';
		}
	}

	list_str += "</tbody></table>";

	$("#top10_list").html(list_str);

	// Fill in Knowledge base results
	var list_arr = knowledge_base.results;
	var list_str = '';

	if(list_arr.length > 0)
	{
		for(var i = 0; i < list_arr.length; i++)
		{
			list_str += '<div>' + unescape(list_arr[i].title) + '&nbsp;<a href="' + list_arr[i].link + '" target="_blank">more</a></div><br />';
		}
	}
	$("#base_list").html(list_str);
	
	// check here if the TYPE selected and if not - select "All Types"
	if(g_type == 'Select Type from dropdown')
	{
		$("#type_list li:first").click();
	}
}

/*
 * Show AVVO Knowledge Base list
 */
function show_base()
{
	$("#link_base").css("color","#800000");
	$("#link_top10").css("color","blue");
	
	$("#top10_header, #top10_header_text, #top10_list").hide();
	$("#base_header, #base_list").show();

}

/*
 * Show AVVO Top-10 Attorneys list
 */
function show_top10()
{
	$("#link_top10").css("color","#800000");
	$("#link_base").css("color","blue");
	
	$("#top10_header, #top10_header_text, #top10_list").show();
	$("#base_header, #base_list").hide();
	
}


////////////////////////////////////////////////////////////////////////////////////////////////////////

// Returns the height of the web page
// (could change if new content is added to the page)
function pageHeight() {
    return document.body.scrollHeight;
}

// Returns the width of the web page
function pageWidth() {
    return document.body.scrollWidth;
}

// A function for determining how far horizontally the browser is scrolled
function scrollX() {
    // A shortcut, in case we’re using Internet Explorer 6 in Strict Mode
    var de = document.documentElement;

    // If the pageXOffset of the browser is available, use that
    return self.pageXOffset ||

        // Otherwise, try to get the scroll left off of the root node
        ( de && de.scrollLeft ) ||

        // Finally, try to get the scroll left off of the body element
        document.body.scrollLeft;
}

// A function for determining how far vertically the browser is scrolled
function scrollY() {
    // A shortcut, in case we’re using Internet Explorer 6 in Strict Mode
    var de = document.documentElement;

    // If the pageYOffset of the browser is available, use that
    return self.pageYOffset ||

        // Otherwise, try to get the scroll top off of the root node
        ( de && de.scrollTop ) ||

        // Finally, try to get the scroll top off of the body element
        document.body.scrollTop;
}

// Find the height of the viewport
function windowHeight() {
    // A shortcut, in case we’re using Internet Explorer 6 in Strict Mode
    var de = document.documentElement;

    // If the innerHeight of the browser is available, use that
    return self.innerHeight ||

        // Otherwise, try to get the height off of the root node
        ( de && de.clientHeight ) ||

        // Finally, try to get the height off of the body element
        document.body.clientHeight;
}

// Find the width of the viewport
function windowWidth() {
    // A shortcut, in case we’re using Internet Explorer 6 in Strict Mode
    var de = document.documentElement;

    // If the innerWidth of the browser is available, use that
    return self.innerWidth ||

        // Otherwise, try to get the width off of the root node
        ( de && de.clientWidth ) ||

        // Finally, try to get the width off of the body element
        document.body.clientWidth;
} 


function base64_decode (data) {
    // Decodes string using MIME base64 algorithm  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/base64_decode    
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman    
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode    
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {    //    return btoa(data);
    //}
 
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; 
    if (!data) {
        return data;
    }
     data += '';
 
    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
         o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
 
        if (h3 == 64) {            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec); 
    return dec;
}

function utf8_decode ( str_data ) {
    // Converts a UTF-8 encoded string to ISO-8859-1  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/utf8_decode    
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'    
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    } 
    return tmp_arr.join('');
}
