var $form_name = 'kernel_form';
var submitted = false;

function redirect($url) {
	window.location.href = $url;
}

function jq($selector) {
	return $selector.replace ? $selector.replace(/(\[|\]|\.)/g, '\\$1') : $selector;
}

function in_array(needle, haystack)
{
	return array_search(needle, haystack) != -1;
}

function array_search(needle, haystack)
{
	for (var i=0; i<haystack.length; i++)
	{
		if (haystack[i] == needle) return i;
	}
	return -1;
}

function get_control($mask, $field, $append, $prepend) {
	$append = $append !== undefined ? '_' + $append : '';
	$prepend = $prepend !== undefined ? $prepend + '_' : '';

	return document.getElementById( $prepend + $mask.replace('#FIELD_NAME#', $field) + $append );
}

function crc32(str) {
	var table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D';

	var crc = 0;
	var x = 0;
	var y = 0;

	crc = crc ^ (-1);

	for (var i = 0, iTop = str.length; i < iTop; i++) {
		y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
		x = "0x" + table.substr( y * 9, 8 );
		crc = ( crc >>> 8 ) ^ x;
	}

	return crc ^ (-1);
}

function getCurrentAnchor() {
	var current_url = window.location.href;
	return current_url.match(/\#/) ? current_url.replace(/^.+\#/, '') : '';
}

function setAnchorParam(name, value, replaceUrl) {
	var anchor = getCurrentAnchor();
	var regexp = new RegExp('^'+name+'=[^&]*');
	var regexp2 = new RegExp('&'+name+'=[^&]*');
	anchor = anchor.replace(regexp, '').replace(regexp2, '');
	anchor += anchor.length > 0 ? '&' : '';
	anchor = anchor.replace('&&', '&');
	anchor += encodeURIComponent(name);
	if (typeof(value) != 'undefined') {
		anchor += '='+encodeURIComponent(value);
	}
	anchor = anchor.replace(/&$/, '').replace(/^&/, '');

	if (replaceUrl) {
		window.location.replace(window.location.href.replace(/\#.*$/, '')+'#'+anchor);
	}
	else {
		window.location.hash = anchor;
	}
}

function getAnchorParam(name)
{
	var ret = false;
	var anchor = getCurrentAnchor();
	var regexp = new RegExp('(^|&)' + name + '=([^&]*)'); // &name=value OR ?name=value (parameter)
	var regexp2 = new RegExp('(^|&)' + name + '([^=]|$)'); // &name OR ?name (mark)

	if (anchor.match(regexp)) {
		var matches = regexp.exec(anchor);
		ret = matches[2];
	}
	else if (anchor.match(regexp2)) {
		ret = true;
	}

	return ret;
}

function update_checkbox(cb, cb_hidden)
{
	cb_hidden.value = cb.checked ? 1 : 0;
}

$(document).ready(
	function () {
		$('body').ajaxComplete(function (ev, request) {
			if (request) {
				var responce = request.responseText;
				if (typeof(responce) == 'string' && responce.match(/^\s*#redirect#/)) {
					ev.preventDefault();
					window.location.href = responce.replace(/^\s*#redirect#/, '');
				}
			}
		});
	}
);

function getDocumentFromXML(xml)
{
	if (window.ActiveXObject) {
		var doc = new ActiveXObject("Microsoft.XMLDOM");
		doc.async=false;
		doc.loadXML(xml);
	}
	else {
		var parser = new DOMParser();
		var doc = parser.parseFromString(xml,"text/xml");
	}
	return doc;
}

function strip_tags(str) {
    var key = '';
    var matches = [];
    var html = '';

    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };

    str += '';

    // Match tags
    matches = str.match(/(<\/?[\S][^>]*>)/gi);

    // Go through all HTML tags
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }

        // Save HTML tag
        html = matches[key].toString();

		str = replacer(html, '', str); // Custom replace. No regexing
    }

    return str;
}

function submit_event($prefix_special, $event, $t)
{
	if (!$event) $event = '';

	set_hidden_field('events[' + $prefix_special + ']', $event);
	if (typeof($t) != 'undefined')  set_hidden_field('t', $t);

	submit_kernel_form();
}

function submit_kernel_form()
{
	if (submitted) {
		return;
	}
	submitted = true;

	var $form = document.getElementById($form_name);

	if (typeof $form.onsubmit == "function") {
		$form.onsubmit();
	}

	$form.submit();

	$form.target = '';
	if (typeof(t) != 'undefined') set_hidden_field('t', t);

	window.setTimeout(function() {submitted = false}, 500);
}

function set_hidden_field($field_id, $value)
{
	var $kf = document.getElementById($form_name);
	var $field = $kf.elements[$field_id];
	if ($field) {
		$field.value = $value;
		return true;
	}

	$field = document.createElement('INPUT');
	$field.type = 'hidden';
	$field.name = $field_id;
	$field.id = $field_id;
	$field.value = $value;

	$kf.appendChild($field);
	return false;
}

function get_hidden_field($field)
{
	var $kf = document.getElementById($form_name);
	return $kf.elements[$field] ? $kf.elements[$field].value : false;
}

function isset(variable)
{
	if(variable==null) return false;
	return (typeof(variable)=='undefined')?false:true;
}

function de(id) {
	return document.getElementById(id);
}

function clickElement(el_name)
{
	oel = document.getElementById(el_name);
	if ((typeof oel.click) == 'function') {
		oel.click();
	} else {
		if ((typeof oel.onclick) == 'function') {
			oel.onclick();
		}
	}
}

function InsertSmiley(sm)
{
	array_id = sm;
 	if (edit_mode) {
	 	image = image_smileys[array_id];
		if (is_msie()) {
			editbox.contentWindow.document.body.innerHTML += '<img src="'+ image_path + image +'" alt="">';
		} else {
			editbox.contentWindow.document.execCommand('InsertImage', false, image_path+image);
		}
		if (document.all) {
			editbox.contentWindow.document.selection.empty();
		}
		editbox.contentWindow.focus();
	}
	else {
		code = codes_smileys[array_id];
		de('input_text').value = de('input_text').value+' '+code;
		document.getElementById('input_text').focus();
	}
	CountChars();
}

function InsertSmiley2(sm)
{
	array_id = sm;
 	if (!is_ff() && edit_mode) {
	 	image = image_smileys[array_id];
		editbox.contentWindow.document.body.innerHTML += '<img src="'+ image_path + image +'" alt="">';
		if (document.all) {
			editbox.contentWindow.document.selection.empty();
		}
		editbox.contentWindow.focus();
	}
	else {
		code = codes_smileys[array_id];
		de('message').value = de('message').value+' '+code;
		document.getElementById('message').focus();
	}
	CountChars();
}

var editbox = '';
var edit_mode = false;

function initEditor() {
	editbox = document.getElementById('edit');
	editbox.contentWindow.document.designMode = "on";
	try {
		editbox.contentWindow.document.execCommand("undo", false, null);
	}
	catch(e) {
	    document.getElementById('div_edit').style.display='none';
	    document.getElementById('div_text').style.display='';
	}
	if(document.addEventListener) {
		document.addEventListener("keyup", CountChars, true);
		editbox.contentWindow.document.addEventListener("keyup",  CountChars, true);
	}
	else if (document.attachEvent) {
		document.attachEvent("onkeyup", CountChars, true);
		editbox.contentWindow.document.attachEvent("onkeyup", CountChars, true);
	}
    editbox.contentWindow.document.innerHTML = '';
    editbox.contentWindow.focus();
}

function GetModeType() {
	if (!document.getElementById('edit')) {
		edit_mode = false;
		return;
	}
	if (document.getElementById('div_text').style.display == 'none')
		edit_mode = true;
	else {
		edit_mode = false;
	}
}

function is_msie() {
	var browser = "";
	browser = navigator.appName;
	if (browser == 'Microsoft Internet Explorer')
		return 1;
	else
		return 0;
}

function is_ff() {
	var browser = navigator.userAgent;
	if (browser.indexOf('Firefox') > 0)
		return 1;
	else
		return 0;
}

function CountChars()
{
	return;
	strText = editbox.contentWindow.document.body.innerHTML;
	strText = strText.replace(/&nbsp;/g, "1");
	strText = strText.replace(/&amp;/g, "1");
	strText = strText.replace(/&quot;/g, "1");
	strText = strText.replace(/&lt;/g, "1");
	strText = strText.replace(/&gt;/g, "1");

	for (var i = 0; i < all_image_smileys.length; i++) {
		var strTarget = all_image_smileys[i];

		if (strText.indexOf(strTarget) != -1) {
			// smiley image is found in message HTML code -> replace it
			strText = strText.replace(new RegExp('<img src="' + image_path + strTarget + '">', 'gi'), all_codes_smileys[i]);
		}
	}

	if (strText.length > mlength - 5) {
		document.getElementById('ml_value').innerHTML = "<font color='#FF0000'>" + strText.length + "</font>";
	} else {
		document.getElementById('ml_value').innerHTML = strText.length;
	}

	if (strText.length > mlength) {
		strText = strText.substring(0,mlength);
		replaceCodeToSmileys(strText);
	}
	//editbox.contentWindow.focus();
}

function do_nothing() {}

function dosearch()
{
	$form_name = 'search_form';
	var a_li = document.getElementsByTagName("li");
	var cats = '';
	for (i=0; i<a_li.length;i++) {
		if (
			(a_li[i].className == "selected" )
			&& (a_li[i].id.substr(0,4) == "cat_") && a_li[i].id != 'cat_all'
		) {
			cats = cats + a_li[i].id.substr(4) + ',';
		}
	}
	if (cats.length > 0) {
		cats = cats.substr(0, cats.length - 1);
	}

	if ( cats == '' ) {
		$('#cat_all').addClass('selected');
	}
	else {
		$('#cat_all').removeClass('selected');
	}

	if ( cats == 'all' ) cats = '';
	set_hidden_field('users-goal_searchparams[0][Categories]', cats);
	submit_event('custom-sections', 'OnKeywordSearch');
}

impose_limits_exceeded = [];

function SpecImposeMaxLength(Object, Event, MaxLen)
{
	var id = Object.id;
	var left = MaxLen - Object.value.length;
	if (left < 0) {
		left *= -1;
		$('#error_msg').html('<span style="color:red">You have exceeded the maximum length by '+left+' characters!</span>');
		if (impose_limits_exceeded[id]) {
			if (Object.value.length < impose_limits_exceeded[id]) impose_limits_exceeded[id] = Object.value.length;
		}
		else impose_limits_exceeded[id] = Object.value.length;
	}
	else {
		$('#error_msg').html(left+' characters left');
		impose_limits_exceeded[id] = 0;
	}
}

function checkImpose(Object, Event, MaxLen) {
	var id = Object.id;
	var len = Object.value.length;
	if (impose_limits_exceeded[id] || len >= MaxLen) {
		var allow = [8,37,38,39,40,46];
		for(var i=0; i<allow.length; i++) if (allow[i] == Event.keyCode) return true;
		return false;
	}
}

function send_form()
{
	$.post(
		$('#contact_us_form').attr('action'),
		$('#contact_us_form').serializeArray(),
		function ($data) {
			$data = eval('('+$data+')');
			for (i=1; i<=3; i++) $('#error_fld_'+i).html("");
			if ($data.status == 'ok') {
				for (i=1; i<=3; i++) $('#fld_'+i).val("");
				window.location.href = $data.next_template;
			}
			else {
				for (field in $data.errors) {
					$('#error_'+field).html($data.errors[field]);
				}
			}
		}
	)
}

function login_window(product_code)
{
	if (typeof product_code == 'undefined') {
		product_code = '';
	}
	FormManager.openForm('u', 'login/login_form', 450, 320, '', {product_code: product_code});
}

function account_window()
{
	FormManager.openForm('u', 'login/account_form', 840, 495);
}

function writing_services_window()
{
	FormManager.openForm('u', 'writing_services', 890, 470);
}

function video_tour_window()
{
	FormManager.openForm('u', 'video_tour', 892, 640);
}


function publishing_options_window()
{
	FormManager.openForm('u', 'publishing_options', 840, 530);
}


function buy_pdf_window()
{
	FormManager.openForm('u', 'buy_pdf', 220, 640);
}


function change_book_window()
{
	FormManager.openForm('book', 'interview/change_book', 880, 525)
}


function show_thank_you(order_id)
{
	FormManager.openForm('memoir', 'thank_you_for_order_screen', 445, 317, 'undefined', {order_id: order_id}, '-no-padding');
}


function replace_modal($func)
{
	TB.remove;
	setTimeout($func, 1000);
}

function register_window()
{
	FormManager.openForm('u', 'login/register_form', 840, 535)
}

function toggle_section(section_id)
{
	var data_div = $(document.getElementById(section_id)).next('div:first');
	var section_a = document.getElementById(section_id + "_a");
	if (section_a.className == 'open-close-1') {
		section_a.className = 'open-close-2';
		data_div.hide();
	} else {
		section_a.className = 'open-close-1';
		data_div.show();
	}
}

function process_field_focus(field_name)
{
	if( $('#'+jq(field_name)).hasClass('input-text-error') ) {
		$('#'+jq(field_name)+'_status_cell').parents('div:first').addClass('hidden-class');
		$('#'+jq(field_name)+'_status_cell').html('');
	}
}

function update_timeline(is_toc)
{
	if (!is_toc) is_toc = 0;
	var url = FormManager.getURL(null, 'elements/timeline', undefined, {
		is_toc: is_toc
	});
	$('#timeline_container').load(url,
		function() {
			var height = $('#first_timeline_row').height() * 0.6;

			$('#timeline_container').find('div.infoblock').each(
				function(i) {
					$(this).css({height:height+'px'});
				}
			);
		}
	);
}

function update_family_timeline()
{
	var url = FormManager.getURL(null, 'elements/family_timeline', undefined);
	$('#family_timeline_container').load(url,
		function() {
			var height = $('#first_family_timeline_row').height() * 0.6;

			$('#family_timeline_container').find('div.infoblock').each(
				function(i) {
					$(this).css({height:height+'px'});
				}
			);
		}
	);
}


function update_progress()
{
	var url = FormManager.getURL('memoir', null, 'OnGetProgressPercent', {});
	$.post(url, {}, function(percent) {
			var obj = document.getElementById("progress_bar");
			if (obj) {
				obj.childNodes[0].style.width = percent;
				obj.childNodes[0].childNodes[0].innerHTML = percent;
				obj.childNodes[1].innerHTML = percent;
			}
		}
		,'text'
	);
}

function remove_bubble()
{
	//$('#popup-welcome-div').hide(2000);
	$('#popup-welcome-div').fadeOut('slow');
}

function do_scroll()
{
	if (current_tab != 9) { // not timeline
		var odiv = $('#tab_scroll_' + current_tab);
		var ocontent = $('#tab_scroll_content_' + current_tab);
//					var offset = ocontent.offset().left;
		var window_width = odiv.width();
		var content_width = ocontent.width();
		var scroll_left = odiv.scrollLeft() + scroll_direction * scroll_step;
		if (scroll_left > content_width - window_width) {
			scroll_left = content_width - window_width;
		}
		if (scroll_left < 0) {
			scroll_left = 0;
		}
		if (scroll_left == 0) {
			$('#tab_scroll_left_'+current_tab).addClass('ta-left-disabled');
		} else {
			$('#tab_scroll_left_'+current_tab).removeClass('ta-left-disabled');
		}
		if (scroll_left >= content_width - window_width) {
			$('#tab_scroll_right_'+current_tab).addClass('ta-right-disabled');
		} else {
			$('#tab_scroll_right_'+current_tab).removeClass('ta-right-disabled');
		}

		if (scroll_direction != 0) {
			odiv.scrollLeft(scroll_left);
		}
	}
	setTimeout(do_scroll, scroll_interval);
}


var next_video_item;
function click_next_video_item()
{
	if (next_video_item.length) {
		next_video_item.click();
	}
}


