// --------------- AJAX-Calls: ---------------------
function getPrayerTimes(latitude, longitude, locationInfo)
{
    // show load icon
    $("#ptContainerId").hide();
    $("#prayTimeLocation").hide();
    var pic = "<img id='loadIcon' src='media/images/ajax_load.gif'/>";
    $("#loadPT").html(pic);
    /*
    $("#loading").ajaxStart(function(){$("#loading").html(pic);$("#ptContainerId").hide()});
    $("#loading").ajaxStop(function(){$("#loadIcon").remove(); $("#ptContainerId").show()});
    */

    $.post("prayer/prayer/getTodaysPrayerTimes", {lat: latitude, lng: longitude},
            function(data)
            {
                if (data.status_code == "PRAYER_RESULT_SUCCESS")
                {
                    $("#ptContainerId").fadeIn('slow');
                    $("#prayTimeLocation").fadeIn('slow');
                    $("#loadIcon").remove();

                    // show location info:
                    if(locationInfo != false)
                    {
                        //$("#prayTimeLocation").html(locationInfo[0]+"&nbsp;&nbsp;"+locationInfo[1]+","+locationInfo[2]);
                        $("#prayTimeLocation").html(locationInfo);
                    }

                    //alert(data.hijri);
                    var prayTimes = getCorrectFormatForTimes(data.pray_times);
                    $("#fadjr").html(prayTimes[0]);
                    $("#shuruk").html(prayTimes[1]);
                    $("#zuhr").html(prayTimes[2]);
                    $("#assr").html(prayTimes[3]);
                    $("#magreb").html(prayTimes[4]);
                    $("#isha").html(prayTimes[5]);

                    // get currently next pray time:
                    // animierter Uebergang und Ezan nicht vergessen!
                    var nextPrayTimeID = getCurrentNextPrayingTime(prayTimes);
                    $("#"+nextPrayTimeID).css("color", "green");

                }
                else if(data.status_code == "PRAYER_UNDER_MAINTENANCE")
                {
                    $("#ptContainerId").fadeIn('slow');
                    $("#loadIcon").remove();
                    $("#ptContainerId").html("Service wird aktuell gewartet!");
                }
                else if(data.status_code == "TIMEZONE_FAILURE")
                {
                    $("#ptContainerId").fadeIn('slow');
                    $("#loadIcon").remove();
                    $("#ptContainerId").html("Timezone error -> Service not available!");
                }
                else
                {
                    $("#ptContainerId").fadeIn('slow');
                    $("#loadIcon").remove();
                    $("#ptContainerId").html("Service aktuell nicht verf&uuml;gbar!");
                }
            }, "json");
}

// Location ccordina
function getLocationCoordinatesFromCookie(location)
{
    $.post("geo/geolocation/getLocationCoordinates", {locationString: location},
            function(data)
            {
                if (data.Status.code == 200)
                {
                    longitude = data.Placemark[0].Point.coordinates[0];
                    latitude = data.Placemark[0].Point.coordinates[1];
                    address = data.Placemark[0].address;
                    /*
                    alert(data.Placemark[0].Point.coordinates[0]);
                    alert(data.Placemark[0].Point.coordinates[1]);
                    alert(data.Placemark[0].AddressDetails.Country.CountryName);
                    alert(data.Placemark[0].AddressDetails.Country.CountryNameCode);
                    alert(data.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName);
                    */
                    getPrayerTimes(latitude, longitude, address);
                    
                    //map.setCenter(new google.maps.LatLng(latitude, longitude), 13);
                }
                else
                {
                    alert("Location could not be found!");
                }
            }, "json");
}

// get random Hadith from kaaba-online:
function getRandomHadith()
{
    var pic = "<div style='margin-left: 300px; margin-top: 50px;'><img id='loadIconHadith' src='media/images/ajax_load.gif'/></div>";
    $("#hadithContent").html(pic);

    $.post("prayer/prayer/getRandomHadith", {},
            function(data)
            {
                $("#loadIconHadith").remove();

                if (data.status_code == "HADITH_SEARCH_SUCCESS")
                {
                    $("#hadithContent").html(data.hadith).css("display", "none");
                    $("#hadithContent").fadeIn("slow");                    
                }
                else
                {
                    $("#hadithContent").html("Hadithe aktuell nicht verf&uuml;gbar!");
                }
            }, "json");    
}

// add visit counter:
function addVisitCounter()
{
    $.post("prayer/prayer/addVisitCounter", {},
            function(data)
            {
                // show todays visitors:
                $("#cnt").html(data.visits);
            }, "json");
}

// get current visit counter:
function getVisitCounter()
{
    $.post("prayer/prayer/getVisitCounter", {},
            function(data)
            {
                // show todays visitors:
                $("#cnt").html(data.visits);
            }, "json");
}

/**
 * Refresh Pray Times and and the actual time:
 */
function refreshTimeAndPrayTime()
{
    var ptimes = new Array();
    ptimes[0] = trim($("#fadjr").html());
    ptimes[1] = trim($("#shuruk").html());
    ptimes[2] = trim($("#zuhr").html());
    ptimes[3] = trim($("#assr").html());
    ptimes[4] = trim($("#magreb").html());
    ptimes[5] = trim($("#isha").html());

    // set new time:
    var myDate = new Date();
    var minutes = myDate.getUTCMinutes();
    if(minutes <= 9)
        minutes = "0"+minutes;
    var currTime = myDate.getHours()+"<font color= #704700>:</font>"+minutes;
    $("#timeId").html(currTime);

    // highlight the next pray time:
    var nextPrayTimeID = getCurrentNextPrayingTime(ptimes);
    if(nextPrayTimeID != false)
    {
        // reset all pray times:
        ($("#fadjr").css("color", "red"));
        ($("#shuruk").css("color", "red"));
        ($("#zuhr").css("color", "red"));
        ($("#assr").css("color", "red"));
        ($("#magreb").css("color", "red"));
        ($("#isha").css("color", "red"));
        $("#"+nextPrayTimeID).css("color", "green");

        // Todo: Ezan muss ausgerufen werden:
        // if a new prayer will be reached play the Ezan:
        //DHTMLSound("/media/sounds/Makkah.wav");
    }

    // show new visit counter:
    getVisitCounter();
}
// playback Ezan sound:
function DHTMLSound(surl)
{
    $("#soundspan").html("<embed src='"+surl+"' hidden=true autostart=true loop=false>");
}

/**
 * receive pray times for the given location:
 * @param location
 */
function getPrayTimesForGivenLocation(location)
{
    // show load icon
    $("#ptContainerId").hide();
    $("#prayTimeLocation").hide();
    var pic = "<img id='loadIcon' src='media/images/ajax_load.gif'/>";
    $("#loadPT").html(pic);

    // check if hometown option is selected:
    var isHomeTown = $("#homeTownCheck").attr('selected')

    // try to get location data:
    $.post("geo/geolocation/getLocationCoordinates", {locationString: location, hometown: isHomeTown},
            function(data)
            {
                if (data.Status.code == 200)
                {
                    var longitude = data.Placemark[0].Point.coordinates[0];
                    var latitude = data.Placemark[0].Point.coordinates[1];
                    var address = data.Placemark[0].address;


                    /*
                    var cityName = data.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                    var countryName = data.Placemark[0].AddressDetails.Country.CountryName;
                    var countryNameCode = data.Placemark[0].AddressDetails.Country.CountryNameCode;
                    var locationInfo = new Array();
                    locationInfo[0] = cityName;
                    locationInfo[1] = countryName;
                    locationInfo[2] = countryNameCode;
                    */
                   
                    // set new location with Google maps:
                    map.setCenter(new google.maps.LatLng(latitude, longitude), 16);

                    // get the actual praying times for the new town:
                    //getPrayerTimes(latitude, longitude, locationInfo);
                    getPrayerTimes(latitude, longitude, address);
                }
                else
                {
                    var ortHtml = "<div style='margin-left: -90px; font-size: 12px; font-weight: bold; width:200px; color: red'>";
                    ortHtml += "Dein Ort konnte nicht gefunden werden. Vielleicht hast du dich einfach nur verschrieben ;)";
                    ortHtml += "</div>";
                    $("#loadPT").html(ortHtml);
                }
            }, "json");    
}

// Toggling Hometown checkbox
function toggleHometownSelect(element)
{
    if($(element).attr('selected') == 'false')
    {
        $(element).css({'background-position' : '0px 0px', "margin-top":"0px", "margin-left":"0px"}).attr('selected', 'true');
    }
    else if($(element).attr('selected') == 'true')
    {
        $(element).css({'background-position' : '0px -42px', "margin-top":"-4px", "margin-left":"3px"}).attr('selected', 'false');
    }
}
// ---------------------------------------------------

// --------------- Functional-Calls: -----------------

// Correct prayer times to German time format:
// Input: prayTimes as Array
function getCorrectFormatForTimes(the_prayTimes)
{
    var hours = new Array(13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);

    // Fadjr	Shuruk	Zuhr	Assr	Magreb	Ischa'a
    // Test input:
    var ptimes = new Array();
    ptimes[0] = removeNL(the_prayTimes.fajr);  // Fadjr
    ptimes[1] = removeNL(the_prayTimes.sunrise);  // Shuruk / Sunrise / Sonnenaufgang
    ptimes[2] = removeNL(the_prayTimes.dhuhr);  // Zuhr
    ptimes[3] = removeNL(the_prayTimes.asr);  // Assr
    ptimes[4] = removeNL(the_prayTimes.maghrib);  // Magreb
    ptimes[5] = removeNL(the_prayTimes.isha);  // Ischa'a

    var compareTime = ptimes[0];
    var compareTimeHour = compareTime.split(":")[0];

    var newTimes = new Array();

    newTimes[0] = compareTime;
    var last = false;

    // iterate through times and correct format: 
    for (i = 1; i < ptimes.length; i++)
    {
        var currentTime = ptimes[i];
        var currentTimeHour = currentTime.split(":")[0];

        if ((parseInt(currentTimeHour) > parseInt(compareTimeHour)) && !last)
        {
            newTimes[i] = currentTime;
            compareTimeHour = ptimes[i].split(":")[0];
        }
        if (parseInt(currentTimeHour) < parseInt(compareTimeHour) || last)
        {
            // split to hour and minute:
            var times = currentTime.split(":");

            // format currentTime to PM German notation:
            var hour = times[0];
            var minutes = times[1];

            newTimes[i] = hours[hour-1]+":"+minutes;
            last = true;
        }
    }
    return newTimes;
}

// get next praying time:
// Input: prayTimes as Array, current prayTime("Fadjr" || "Shuruk" || .....)
// Return: prayTime("Fadjr" || "Shuruk" || .....) -> if same as input then false! 
function getCurrentNextPrayingTime(ptimes)
{
    if(ptimes == null || ptimes == false || ptimes == undefined || ptimes[0] == undefined)
        return false;

    // Fadjr	Shuruk	Zuhr	Assr	Magreb	Ischa'a
    // Test input:
    var inputPrayer = "XXXX";

    var currentDate = new Date();
    var currentHour = currentDate.getHours();
    var currentMinutes = currentDate.getMinutes();
    var prayerID = new Array("fadjr", "shuruk", "zuhr", "assr", "magreb", "isha");

    // iterate through times and correct format:
    for (i = 0; i < ptimes.length; i++)
    {
        var prayerTimeHour = ptimes[i].split(":")[0];
        var prayerTimeMinutes = ptimes[i].split(":")[1];

        if(parseInt(currentHour) < parseInt(prayerTimeHour))
        {
            if(prayerID[i] == inputPrayer)
                return false;
            else
                return prayerID[i];
        }
        else if(parseInt(currentHour) == parseInt(prayerTimeHour))
        {
            // ahh minutes have to be compared:
            if(parseInt(currentMinutes) <= parseInt(prayerTimeMinutes))
            {
                if(prayerID[i] == inputPrayer)
                    return false;
                else
                    return prayerID[i];                
            }
        }
    }
    return false;
}
// ---------------------------------------------------

// --------------- Helper-Calls: ---------------------
// show div with effect:
function showDivWithEffect(divToShow, divsToHide)
{
    for (i = 0; i < divsToHide.length; i++)
    {
        //$("#"+divsToHide[i]).css("background-color", "white");
        $("#" + divsToHide[i]).hide();
    }
    $("#" + divToShow).fadeIn("slow");
}


// show hide specified div container with effect!
function showHideDivContainer(id)
{
    //$("#"+id).toggle("fast");
    if ($("#" + id).is(":hidden"))
    {
        $("#" + id).slideDown("fast");
    }
    else
    {
        $("#" + id).slideUp("fast");
    }
}

// trim function
function trim(zeichenkette)
{
    // Erst führende, dann Abschließende Whitespaces entfernen
    // und das Ergebnis dieser Operationen zurückliefern
    if(zeichenkette != null && zeichenkette != false && zeichenkette != undefined)
    	return zeichenkette.replace(/^\s+/, '').replace(/\s+$/, '');
}

function removeNL(s)
{
if(s != null && s != false && s != undefined)
  return s.replace(/[\n\r\t]/g,"");
}

// / Input helping text set / reset:
function clearInput(id, value, template)
{
    if(value == template)
    {
        $("#"+id).val("");
        $("#"+id).css("color","black");
    }
}

function resetInput(id, value, template)
{
    if(value == "" || value == undefined)
    {
        $("#"+id).val(template);
        $("#"+id).css("color","#B3B3B3");
    }
}

// read cookie:
function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// Calculating Qibla location, based on the given target location:
// Source for formula = http://www.scribd.com/doc/3016974/SKMM-08-QIBLA
/*
sin^-1: Math.asin(x);
cos^-1: Math.acos(x);
tan^-1: Math.atan(x);
cot: 1/tan(x);
 */
function calculateQiblaLocation(latitude, longitude)
{
    latitude =  52.5234;
    longitude = 13.4114;

    var qiblaLatitude = 21.4225;
    var qiblaLongitude = 39.8261;

    var a = 90 - latitude;
    var b = 90 - qiblaLatitude;
    var C = longitude - qiblaLongitude;

    // Formula:
    var form1 = Math.sin(bogenmass(C)) / ( Math.sin(bogenmass(a)) * (1/Math.tan(bogenmass(b))) - (Math.cos(bogenmass(a)) * Math.cos(bogenmass(C))));

    var richtungBogenmass = Math.atan(form1);


    var qiblaAzimuth1 = 180 - fromBogenToGrad(richtungBogenmass);
    var qiblaAzimuth2 = fromBogenToGrad(richtungBogenmass);
    alert("qiblaAzimuth = "+qiblaAzimuth2+", 180 - qiblaAzimuth = "+qiblaAzimuth1);

    return qiblaAzimuth;
}

// PolyEndpoints to draw line to location:
function showCoordinates(hypoLength, qiblaAzimuth)
{
    var locationPoints = array();
    var x = Math.cos(bogenmass(qiblaAzimuth)) * hypoLength;
    var y = Math.sin(bogenmass(qiblaAzimuth)) * hypoLength;
    locationPoints[0] = x;
    locationPoints[1] = y;

    return locationPoints;
}

// convert angle to Bogenmass:
function bogenmass(grad)
{
    var bogenmass = grad*Math.PI/180;
    return bogenmass;    
}

// convert Bogenmass to angle:
function fromBogenToGrad(bogenmass)
{
    grad = (bogenmass*180) / Math.PI;
    return grad;
}
// ---------------------------------------------------
