var results = {};
var wind = $j(window).get(0);//.opener ? window.opener : window;
var doc = wind.document;

/* This utility function resolves the string movieName to a Flash object reference based on browser type. */
$j.getMovieName = function(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return wind[movieName];
	} else {
		return wind.document[movieName];
	}
}
$j.callExternalInterface = function(code, result, resx, resy, type) {
/* Call a function registered as callPlayBall in the SWF named myMovie. */
	switch (type) {
		case 1:
			$j.getMovieName("pmwsz").callPlayLocation(code, result, resx, resy);
			break;
		case 2:
			//$j.getMovieName("pmwsz").callPlayCenterTo(resx, resy);
			$j.getMovieName("pmwsz").callPlayLocationGeo(code, result, resx, resy);
			break;
		case 3:
			$j.getMovieName("pmwsz").callPlayCenterTo(resx, resy);
			break;
		case 4:
			$j.getMovieName("pmwsz").callPlayGeoLocations(result);
			break;
	}
}
function goHere() {
		if ($j.locat !== undefined && $j.latit !== undefined && $j.longit !== undefined) {
			if ($j.latit > 180 || $j.longit > 180) {
				$j.callExternalInterface(2, $j.locat, $j.latit, $j.longit, 1);
			} else {
				$j.callExternalInterface(2, $j.locat, $j.longit, $j.latit, 2);
			}
		} else if ($j.latit !== undefined && $j.longit !== undefined) {
			$j.callExternalInterface(2, '', $j.latit, $j.longit, 3);
		} else if ($j.coourl !== undefined) {
			$j.callExternalInterface(2, $j.coourl, '', '', 4);
		} else if ($j.addr != undefined) {
			$j.search($j.addr);
		}	
	}
$j(document).ready(function() {
	$j.displayResult = function(exclude) {
        $j('#search_string', doc).val(results[exclude].rezultat);
        if (results[exclude].rezultat != "FARA REZULTAT") {
            $j.callExternalInterface(results[exclude].code, results[exclude].rezultat, results[exclude].rezx, results[exclude].rezy, 1);
        }
        $j('#other_results option:gt(0)', doc).remove();
        if (results != null) {
            $j.each(results, function(nr, result) {
                if (nr != exclude) {
                    $j('<option value="' + nr + '">' + result.rezultat + '</option>').appendTo('#other_results', doc);
                }
            });
        }
	}

	$j.manageHistory = function(history) {
        /*if (history != null) {
            if ($j('#historydiv tbody').length) {
                container = '#historydiv tbody';
            } else {
                container = '#divbox tbody';
            }
            $j(container).children().remove();
            var rows = 0;
            $j.each(history, function(query, result) {
                rows++;
                $j('<tr><td class="history' + (rows % 2 ? "odd" : "even") + 'td">' + query + '</td><td class="history' + (rows % 2 ? "odd" : "even") + 'td">' + result + '</td><td class="historyimgtd"><a href="#"><img src="resources/images/history_go' + (result == 'FARA REZULTAT' ? '_dis.png" alt="N/A: Arată locația pe hartă"' : '.png" alt="Arată locația pe hartă"') + ' /></a></td></tr>').appendTo(container);
            });
            $j('a:has(img[src$="_go.png"])').bind('click', function() {
                $j.search($j(this).parent().siblings('td:eq(0)').html());
                return false;
            });
        }*/
		window.open('history.php', 'Istoric', 'width=700,height=200,toolbar=no,location=no,resizable=no,scrollbars=yes,directories=no,status=no,menubar=no');
	}

	$j.search = function(query_string) {
	    if (arguments.length == 0) {
            query_string = $j('#search_string').val();
		}		
		//alert($j('#loading', doc).get(0).);
		$j('#loading', doc).css('display', 'inline');
		//console.log($j('#loading', doc));
        $j.ajax({
            data: {
                query_string: query_string
            },
            dataType: "json",
            error: function(a, b, c) {
                alert(a + b + c);
            },
            success: function(response, textStatus) {
				results = response.results;
				$j.displayResult(0);
				//$j.manageHistory(response.history);
				$j('#loading', doc).css('display', 'none');
            },
            type: "GET",
            url: "query.php"
        });
    }
	/*function(history, options) {
		options = $j.extend({container: "tcontent4", histWrap: "span", histSep: "<br />"}, options);
		$j('#' + options.container + ' ' + options.histWrap + ' #' + options.container + ' ' + /<([a-zA-Z]*)\s/.exec(options.histSep)[1]).remove();
		$j.each(history, function() {
			$j('#' + options.container).append($j('<' + options.histWrap + '>' + this.string + ' - ' + this.time + '</' + options.histWrap + '>' + options.histSep));
		});
	}*/

	$j('#search').click(function() {
		if ($j.inArray($j('#search_string').val(), ['', 'FARA REZULTAT', 'strad\u0103, nr.']) != -1) {
			alert('Introduceti numele unei strazi si/sau numarul!');
			return false;
		}
	    $j.search();
	    return false;
	});

	$j('#other_results').change(function() {
        display = $j(this).val();
	    if (display != '') {
            $j.displayResult(display);
        }
    });

	$j('a:has(img[src$="_go.png"])').bind('click', function() {
        $j.search($j(this).parent().siblings('td:eq(0)').html());
        return false;
	});


    /*$j('[title*="Istoric căutare"]').click(function() {
		if (!$j('#historydiv').dialog('isOpen')) {
			$j('#historydiv').dialog('open');
		} else {
			$j('#historydiv').dialog('close');
		}
		return false;
	});*/

	$j('#search_string, #news_email').click(function() {
		$j(this).select();
	});

	$j('#search_string').keypress(function(event) {
		if (event.which == 13) {
			$j.search();
		}
	});

	$j('#news_subscribe').click(function() {
	   if (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($j('#news_email').val())) {
	       $j.ajax({
	           url: 'newsletter.php',
	           data: {
	               email: $j('#news_email').val()
	           },
	           dataType: 'text',
	           success: function(message, textStatus) {
	               $j('#news_email').val('');
	               alert(message);
	           },
	           type: 'post'
	       });
	   } else {
	       alert('Va rugam introduceti o adresa de email valida!');
	   };
	});
	
	$j('a[href="contact.html"]').click(function() {
		window.open('contact.html', 'Contact', 'width=523,height=308,toolbar=no,location=no,resizable=no,scrollbars=no,directories=no,status=no,menubar=no');
		return false;
	});
	$j('a[href="termeni.html"]').click(function() {
		window.open('termeni.html', 'Termeni', 'width=650,height=500,toolbar=no,location=no,resizable=no,scrollbars=yes,directories=no,status=no,menubar=no');
		return false;
	});
	$j('a[href="history.php"]').click(function() {
		window.open('history.php', 'Istoric', 'width=700,height=200,toolbar=no,location=no,resizable=no,scrollbars=yes,directories=no,status=no,menubar=no');
		return false;
	});
	//.dialog({resizable: 'se', width: '650px', autoOpen: false, position: ['center', 10]});
});
