/*
 *
 */
var bool_mayTouch = false;
var bb_successCallback;
var bb_errorCallback;
function handleBlackBerryLocation()
{
	if (bb_successCallback && bb_errorCallback)
	{
		if(blackberry.location.latitude==0 && blackberry.location.longitude==0)
		{
			//http://dev.w3.org/geo/api/spec-source.html#position_unavailable_error
			//POSITION_UNAVAILABLE (numeric value 2)
			bb_errorCallback({message:"Position unavailable", code:2});
		}
		else
		{

                 
                    
			var timestamp=null;
			//only available with 4.6 and later
			//http://na.blackberry.com/eng/deliverables/8861/blackberry_location_568404_11.jsp
			if (blackberry.location.timestamp)
			{
				timestamp=new Date(blackberry.location.timestamp);
			}
			bb_successCallback({timestamp:timestamp, coords: {latitude:blackberry.location.latitude,longitude:blackberry.location.longitude}});
		}
		//since blackberry.location.removeLocationUpdate();
		//is not working as described http://na.blackberry.com/eng/deliverables/8861/blackberry_location_removeLocationUpdate_568409_11.jsp
		//the callback are set to null to indicate that the job is done

		bb_successCallback = null;
		bb_errorCallback = null;
	}

}

var geo_position_js=function() {



	var pub = {};
	var provider=null;


	pub.getCurrentPosition = function(successCallback,errorCallback,options)
	{

		provider.getCurrentPosition(successCallback, errorCallback,options);

	}

	pub.init = function()
	{

		try
		{
			if (typeof(geo_position_js_simulator)!="undefined")
			{
				provider=geo_position_js_simulator;
			}

             else if(typeof(window.blackberry)!="undefined" && blackberry.location.GPSSupported)
			{

				// set to autonomous mode
				blackberry.location.setAidMode(2);

				//override default method implementation
				pub.getCurrentPosition = function(successCallback,errorCallback,options)
				{

					//passing over callbacks as parameter didn't work consistently
					//in the onLocationUpdate method, thats why they have to be set
					//outside
					bb_successCallback=successCallback;
					bb_errorCallback=errorCallback;
					//function needs to be a string according to
					//http://www.tonybunce.com/2008/05/08/Blackberry-Browser-Amp-GPS.aspx
                                            
					blackberry.location.onLocationUpdate("handleBlackBerryLocation()");
					blackberry.location.refreshLocation();

				}
				provider=blackberry.location;

			}


			else if (typeof(bondi)!="undefined" && typeof(bondi.geolocation)!="undefined")
			{
				provider=bondi.geolocation;
			}
			else if (typeof(navigator.geolocation)!="undefined")
			{
				provider=navigator.geolocation;
				pub.getCurrentPosition = function(successCallback, errorCallback, options)
				{

					function _successCallback(p)
					{
                                       
						//for mozilla geode,it returns the coordinates slightly differently
						if(typeof(p.latitude)!="undefined")
						{
							successCallback({timestamp:p.timestamp, coords: {latitude:p.latitude,longitude:p.longitude}});

						}
						else
						{
							successCallback(p);
						}

					}
					provider.getCurrentPosition(_successCallback,errorCallback,options);
				}


			}
			else if(typeof(window.google)!="undefined"||typeof(google.gears)!="undefined")
			{
				provider=google.gears.factory.create('beta.geolocation');
                      
			}



			else if (typeof(window.Mojo)!="undefined" && typeof(Mojo.Service.Request)!="Mojo.Service.Request")
			{
				provider=true;
				pub.getCurrentPosition = function(successCallback, errorCallback, options)
				{

				parameters={};
				if(options)
				{
					 //http://developer.palm.com/index.php?option=com_content&view=article&id=1673#GPS-getCurrentPosition
					 if (options.enableHighAccuracy && options.enableHighAccuracy==true)
					 {
						parameters.accuracy=1;
					 }
					 if (options.maximumAge)
					 {
						parameters.maximumAge=options.maximumAge;
					 }
					 if (options.responseTime)
					 {
						if(options.responseTime<5)
						{
							parameters.responseTime=1;
						}
						else if (options.responseTime<20)
						{
							parameters.responseTime=2;
						}
						else
						{
							parameters.timeout=3;
						}
					 }
				}


				 r=new Mojo.Service.Request('palm://com.palm.location', {
				 	method:"getCurrentPosition",
				 	    parameters:parameters,
				 	    onSuccess: function(p){successCallback({timestamp:p.timestamp, coords: {latitude:p.latitude, longitude:p.longitude,heading:p.heading}});},
				 	    onFailure: function(e){
								if (e.errorCode==1)
								{
									errorCallback({code:3,message:"Timeout"});
								}
								else if (e.errorCode==2)
								{
									errorCallback({code:2,message:"Position Unavailable"});
								}
								else
								{
									errorCallback({code:0,message:"Unknown Error: webOS-code"+errorCode});
								}
							}
				 	    });
				}

			}
			else if (typeof(device)!="undefined" && typeof(device.getServiceObject)!="undefined")
			{
				provider=device.getServiceObject("Service.Location", "ILocation");

				//override default method implementation
				pub.getCurrentPosition = function(successCallback, errorCallback, options)
				{
					function callback(transId, eventCode, result) {
					    if (eventCode == 4)
						{
					        errorCallback({message:"Position unavailable", code:2});
					    }
						else
						{
							//no timestamp of location given?
							successCallback({timestamp:null, coords: {latitude:result.ReturnValue.Latitude, longitude:result.ReturnValue.Longitude, altitude:result.ReturnValue.Altitude,heading:result.ReturnValue.Heading}});
					 	}
					}
					//location criteria
				    var criteria = new Object();
    				criteria.LocationInformationClass = "BasicLocationInformation";
					//make the call
					provider.ILocation.GetLocation(criteria,callback);
				}
			}

		}
		catch (e){ }

		return  provider!=null;
	}


	return pub;
}();


function sha_geo_position_check() {

// var providerName = false;
 var hasLocation = false;

if(typeof(window.blackberry)!="undefined" && blackberry.location.GPSSupported) {
//providerName='blackberry';
hasLocation = true;
return true;
}

if (typeof(bondi)!="undefined" && typeof(bondi.geolocation)!="undefined") {
provider=bondi.geolocation;
//providerName='bondi';
hasLocation = true;
}

if (typeof(navigator.geolocation)!="undefined") {
providerName='navigator';
hasLocation = true;
}


if(typeof(window.google)!="undefined") {
//providerName='gears';
hasLocation = true;
}

if(typeof(google)!='undefined'&&typeof(google.gears)!="undefined") {
    //providerName='gears';
hasLocation = true;
}



if (typeof(window.Mojo)!="undefined" && typeof(Mojo.Service.Request)!="Mojo.Service.Request") {
//providerName='mojo';
hasLocation = true;
}




if (typeof(device)!="undefined" && typeof(device.getServiceObject)!="undefined") {

//providerName='ilocation';
hasLocation = true;

}

	return hasLocation;
}

function sha_checkAndStorejGPS() {


    if(hasajax==true) {

    res = sha_geo_position_check();

    sha_pushValues('jgps='+res,false);

        if(res==true) {

            getGPS();
        }
    }
}

 function sha_checkjGPS() {


    if(hasajax==true) {

    res = sha_geo_position_check();


    sha_pushValues('jgps='+res,false);


    }
}

function getEvents() {
	 
		if (httpGetEvents.readyState == 4 || httpGetEvents.readyState == 0) {
			 

            prot = window.location.protocol;

            if(prot=='') {
                prot = 'http:';
            }

			httpGetEvents.open("GET",prot+"//"+window.location.hostname+"/ajax/listener.php", true);

			httpGetEvents.onreadystatechange = handlehttpGetEventsListener ;
			
		   	param = "action=getLatestEntries&latestID=";
		   	//httpGetEvents.setRequestHeader("Content-Length",0);
			
			httpGetEvents.setRequestHeader("Connection", "close"); 
		 
			httpGetEvents.send(param); 
		
		}
}


function handlehttpGetEventsListener() {

 
	if (httpGetEvents.readyState == 4) {
		try {
		response = httpGetEvents.responseXML.documentElement;
        } catch (err) {
            response = null
        }
        
        if(response != null) {
            mb = response.getElementsByTagName('mb')['0'].firstChild.nodeValue;

            if(mb>0) {
            //alert(mb);
             //doSound("sound1");
             try {
             sha_ax_ibox(mb);
             } catch ($e) {

             }
            // have new inbox event
            }


            wh = response.getElementsByTagName('wh')['0'].firstChild.nodeValue;

            if(wh>0) {
            //alert(mb);

             try {
             sha_ax_whisp(wh);
             } catch ($e) {

             }

            }


            vc = response.getElementsByTagName('vc')['0'].firstChild.nodeValue;

            if(vc>0) {
            //alert(mb);
             try {
             sha_ax_voic(vc);
             } catch ($e) {
                 
             }
            }

           // alert(vc);
           // alert(mb);
           // alert(wh);
        // alert(parseInt(vc+mb+wh));

            if( parseInt(vc+mb+wh)>0) {
              //doSound("sound1");
            }


            
        }
	}
	//setTimeout('getEvents();',5000); 
}


/*
 */




function sha_pushValues(params) {
	 
		if (httpGetEvents.readyState == 4 || httpGetEvents.readyState == 0) {
			 

            prot = window.location.protocol;

            if(prot=='') {
                prot = 'http:';
            }

			httpGetEvents.open("GET",prot+"//"+window.location.hostname+"/ajax/listener.php?action=push&"+params, true);
 
		   	param = "action=push&"+params;
		   	
			
			httpGetEvents.setRequestHeader("Connection", "close"); 
		 
			httpGetEvents.send(param);
		
		}
}

 

/*
 **/


function getNewContent() {
  //  if(rld_status==false) {
  //      document.location.href = document.location.href;
  //  }
}

function stopRld() {
    rld_status = true;
}

function startRld() {
    rld_status = false;
}

function h_getIbEl() {
    return document.getElementById('ib');
}

function h_getVcEl() {
    oEl = document.getElementById('vc');



    if(oEl==null) {

       othrEl = h_getIbEl().parentNode.cloneNode(true);



       othrEl.getElementsByTagName('img')['0'].setAttribute('id','vc');
       othrEl.getElementsByTagName('img')['0'].src = '/css/ic/pk.png';

       othrEl.href = '/v/ci.php';


       document.getElementById('tm').insertBefore(othrEl,document.getElementById('tm').lastChild);
    }
    return document.getElementById('vc');
}

function h_getWhEl() {
    oEl = document.getElementById('wh');

    if(oEl==null) {
     
       othrEl = h_getIbEl().parentNode.cloneNode(true);
         
      

       othrEl.getElementsByTagName('img')['0'].setAttribute('id','wh');
       othrEl.getElementsByTagName('img')['0'].src = '/css/ic/pp.png';
       
       othrEl.href = '/w.php';

       
       document.getElementById('tm').insertBefore(othrEl,document.getElementById('tm').lastChild);
    }
    return document.getElementById('wh');
}


function sha_ax_ibox(cnt){

        oIb = h_getIbEl();

        //oIb.src = '/css/ic/m/'+cnt+'.png';
        oIb.style.backgroundImage =  "url('/css/ic/m/"+cnt+".png')";
}

 
function sha_ax_voic(cnt){

        oIb = h_getVcEl();
        oIb.style.backgroundImage =  "url('/css/ic/t/"+cnt+".png')";
}


function sha_ax_whisp(cnt){

        oIb = h_getWhEl();
         oIb.style.backgroundImage =  "url('/css/ic/w/"+cnt+".png')";
}


function actForm() {
	try { 
	document.getElementById("act").focus();
	} catch (err) {
	// be quiet // its ok to be null 
	}
}


var gps_boolInfo = false;

function getGPS(withInfo) {
 
if(withInfo!=undefined) {

    if(withInfo==true) {
    bool_doInfo = true;
    } else {
    bool_doInfo = false;
    }


} else {
    bool_doInfo = false;
}
gps_boolInfo = bool_doInfo;
 

if(geo_position_js.init()){


    if(bool_doInfo==true) {
       
           txt = document.createTextNode('Deine Geo-Koordinaten werden jetzt ermittelt. Bitte warte einen kleinen Moment.');

   
    sp = document.createElement('span');
    sp.setAttribute('class','txt');
    sp.appendChild(txt);
        //orig = document.getElementById('gpslink');


       // sha_resetChilds('wo_bin_ich');



        sha_resetChilds('gaddr');
       
        sha_resetChilds('glbs');
 
         var content = document.createElement('div');

         content.appendChild(sp);


        var tg = document.getElementById('wo_bin_ich');
        tg.appendChild(content);
    }



    geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true,maximumAge:0});

} else {

     if(bool_doInfo==true) {
            var la = document.getElementById('gpslink');
            var inr = document.createElement('<br />'); 
            la.appendChild(inr);
 
            var lu = document.getElementById('gpslink');
            lu.appendChild(document.createTextNode('Leider steht diese Funktion auf Deinem Handy nicht zur Verfügung.'));
     }
     
}

function success_callback(p) {

lat = p.coords.latitude.toFixed(6);
lon = p.coords.longitude.toFixed(6)

//document.location.href = "/index.php?lt="+lat+"&lo="+lon;
sha_cbCcntr=1;
shaCbContext = 'jgps';
 
sha_io('lt='+lat+'&lo='+lon,'','rvGeo','');


}



function error_callback(p) {

    var errMsg = '';
    if(p.message!=undefined) errMsg = ' ('+p.message+')';

    if(gps_boolInfo==true) document.getElementById('gpslink').appendChild(document.createTextNode('Leider konnten GPS-Koordinaten nicht ermittelt werden '+errMsg+'.'));

 }


  /* if(window.blackberry && blackberry.location.GPSSupported) {

 

   document.getElementById('gpslink').appendChild(document.createTextNode('Deine GPS-Koordinaten werden ermittelt. Bitte warte einen kleinen Moment.'));

    blackberry.location.onLocationUpdate("sha_bb_Location()");
    
    blackberry.location.refreshLocation();


    }*/
}


function shaRegistration() {

//sha_cbCcntr=1;


//shaNextCb = 'reqAlias';
//sha_device_brand = 'uni';
//nextCb = 'renAlias';
//getGPS();

renewAlias();

}

function renewAlias() {
    
    
     
    //shaNextCb = 'renAlias';
    //sha_io('','','renAlias');
     

    if(geo_position_js.init()){
        geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true});
    }

    function success_callback(p) {

        lat = p.coords.latitude.toFixed(6);
        lon = p.coords.longitude.toFixed(6)

        

        //document.location.href = "/index.php?lt="+lat+"&lo="+lon;
        sha_cbCcntr=1;

        shaNextCb = 'renAlias';
        sha_io('lt='+lat+'&lo='+lon,'','renAlias');

    }

    function error_callback(p) {
     

       if(gps_boolInfo==true) document.getElementById('gpslink').appendChild(document.createTextNode('Leider konnten GPS-Koordinaten nicht ermittelt werden.'));

     }



}

function sha_bb_Location() {


        lat = blackberry.location.latitude;
        lon = blackberry.location.longitude;
        if(lat==0&&lon==0) {
            return false;
        } else {
        document.location.href = "/index.php?lt="+lat+"&lo="+lon+"&ts="+blackberry.location.timestamp+"&dogps=on";
         return true;
        }
   

}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var touchDisplay,origX;
touchDisplay = false;

origX = 0;






function touchHandler (e) {



    if(e.type =='touchstart') {
        touchDisplay = true;
        if(e.touches.length == 1) {
            var touch = e.touches[0];
            origX = touch.pageX;
           
            //document.getElementById()

            if(touch.target.onclick) {
                touch.target.onclick();
            }
        }
    }

    else if(e.type == 'touchmove') {
    
    e.preventDefault();
 

        if(e.touches.length == 1) {

            var touch = e.touches[0];

            var currentX = touch.pageX;
              var moveX = Math.abs(currentX - origX);

            if(origX < currentX ) {


                if(moveX > 100) {

                    sha_page_ff();

                }
            } else {


                if(moveX > 100) {
                 sha_page_rw();
                }
            }


        }

    } else if (e.type =='touchend'||e.type =='touchcancel') {
        touchDisplay  =false;
    }

}


function sha_page_ff() {
     
    document.location.href = document.getElementById('pgff').href;
}

function sha_page_rw() {
    document.location.href = document.getElementById('pgrw').href;
}
