/*  Controls.js : Handles main site functions
 *   Note: please remove comments from code once implemented
 */ 

function createCookie(name, value, days) {             
	if (days) {                 
		var date = new Date();                 
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));                 
		var expires = "; expires=" + date.toGMTString();             
	}             
	else 
		var expires = "";              
	document.cookie = name + "=" + value + expires + "; path=/";         
}          
	
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;         
}          

function eraseCookie(name) {             
	createCookie(name, "", -1);         
} 



function SetLocation(){
/* This function should retrieve the locality 
   information from a database or external site
   and set the following location hash values:

        location.regionName : State or Prividence
        location.cityName   : City
        location.zipCode    : Zip Code
*/


    var location = {};
    var tmp = $('#ZipCodeShown').val();
	var rg = new RegExp('^[0-9]+$', 'ig');

    // Beginning of FAKE data : Call should be made to return data

    if (rg.test(tmp)){
    	$.post('/custom/get_location.php',{zip: tmp}, function(data){
     		location.cityName = data.city;
        	location.regionName = data.state; 
        	location.zipCode = tmp;
        	$('#ZipCodeShown').addClass('hiddenfield');
    		$('#ZipCodeMsg').html('');
        	InitZip(location);
        },"json");		
    } else {
		//Parse the location
		var l = new Array();
		
		l = tmp.split(' ');
		
		var zip = l.pop();
		var state = l.pop();
		var city = l.join(' ');
		
		location.cityName = city.replace(',','');
        location.regionName = state;
        location.zipCode = zip;
        $('#ZipCodeShown').addClass('hiddenfield');
    	$('#ZipCodeMsg').html('');
        InitZip(location);
    }
    // End of FAKE DATA
}


function NewLocation(){

    var defmsg = ' <a id="SetZipCode">Set</a>';
    $('#ZipCodeBtn').html(defmsg);
    $('#ZipCodeShown').removeClass('hiddenfield');

    if ($('#ZipCodeShown')){
        $('#ZipCodeShown').focus(function(){
            if ($(this).get('value') == "Enter Your Location"){
                $(this).set('value','');
            }
        });    
        $('#ZipCodeShown').blur(function(){
            if ($(this).val() == ""){
                $(this).val('Enter Your Location');
            }
        });    
        if ($('#SetZipCode')){
            $('#SetZipCode').click(function(){
               SetLocation();
            });
        }
    }

}

function InitZip(data){

	var rg = new RegExp('^[a-zA-Z]{2}$', 'ig');
	if (!rg.test(data.regionName)){
		var r = data.regionName.toLowerCase().capitalize();	
	}

    var defmsg = data.cityName + ', ' + data.regionName + ' ' + data.zipCode  + ' <a id="ResetZipCode">Reset Location</a>';
	
    if($('#ZipCodeBtn')){
        $('#ZipCodeBtn').html(defmsg);
    }

    if ($('#SetZipCode')){
        $('#SetZipCode').click(function(){
            NewLocation();            
        });
    }
    
    if ($('#ResetZipCode')){
        $('#ResetZipCode').click(function(){
            eraseCookie('shopmychoicezip');
			eraseCookie('shopmychoiceregion');
			eraseCookie('shopmychoicecity');
			window.location.href = window.location.href;
        });
    }    
	
	createCookie('shopmychoicezip',data.zipCode);
	createCookie('shopmychoiceregion',data.regionName);
	createCookie('shopmychoicecity',data.cityName);

}

function GoToURL(url){

    if (Browser.ie){
        //alert('clicked on link for IE hacked url:  ' + url);
        //Ugly hack for ie6 browser
        setTimeout(function(){
	        window.location = url;
        },0);
    } else {
	    window.location.href = url;
    }

}

function InitMenus(){

    //alert('initing menus');	
	
}

function GetLocation(){
    var defmsg = ' <a id="SetZipCode">Set</a>';
    $('#ZipCodeMsg').html('Enter your zipcode: ');
    $('#ZipCodeBtn').html(defmsg);
    $('#ZipCodeShown').removeClass('hiddenfield');
    $('#SetZipCode').click(function(){
        SetLocation();
    });
}


function Search(){
        var term = $('#search_keyword').val();
        var uri = new URI();
        var ex = uri.get('file');
        var reg = uri.getData('state');
        if (ex.test(SHOPURL+'$')){
            SearchTerm(term,reg);
        } else {
		    GoToURL(SHOPURL + '?st=' + escape(term)); 	
        }
}



$(document).ready(function(){
	
	
	//Look for cookie variables to help set location if possible
	if (readCookie('shopmychoicezip')){
		var loc = {};
		loc.zipCode    = readCookie('shopmychoicezip');
		loc.regionName = readCookie('shopmychoiceregion');
		loc.cityName   = readCookie('shopmychoicecity');
		InitZip(loc);
	} else {
		GetLocation();	
	}
	

    //starts the panel in closed state  
	$('#login').css('height','auto');
	$('#login').hide();  

    //Configures the login button to open the panel
    $('#toggleLogin').click(function(e){
        if($(this).html() == 'Log In or Register'){
		    $('#login').toggle();
		    e.preventDefault();
        } else {
            $("body").append("<form id=logout_form method=post><input type=hidden name=lgn_out value=1></form>");
            $("#logout_form").submit();
        }
	});

    //Configures the close panel button
    $('#closeLogin').click(function(e){
		$('#login').hide();
		e.preventDefault();
	});


    //Configure some additional Menu Items
//    $('#lpSubmit, #memLogin').click(function(e){
//        Login(); 
//    }); 
	
	$('#register').click (function(e){
        Register(); 
    }); 
	
//	$('#search').click(function(e){
//		Search();
//    }); 


	//Initialize top and bottom menus
	InitMenus();


    //Configure front page slide show
    if ($('#mpps').length){
		var showDuration = 6000;
		var container = $('#mpps');
		var images = container.find('img');
		var images2 = new Array();
		var currentIndex =0;
		var interval;
		
        var i=0;
		images.each(function(){
			if(i > 0){
				$(this).css('opacity',0);
			}
            i++;
            images2[images2.length] = $(this);
		});
		
		var show = function(){
			images2[currentIndex].animate({opacity:0}, 1000);
			currentIndex = currentIndex < images2.length - 1 ? currentIndex+1 : 0;
			images2[currentIndex].animate({opacity:100}, 1000);
		};
		
		interval = setInterval(show, showDuration);

    }
	
    if ($('#ttmy').length){
		var showDurationt = 7000;
		var containert = $('#ttmy');
		var texts = containert.find('.ttmy_cont');
		var texts2 = new Array();
		var currentIndext =0;
		var intervalt;
		
        var it=0;
		texts.each(function(){
			if(it > 0){
				$(this).css('opacity',0);
			}
            it++;
            texts2[texts2.length] = $(this);
		});
		
		var showt = function(){
			var auxcit = currentIndext;
			currentIndext = currentIndext < texts2.length - 1 ? currentIndext+1 : 0;
			texts2[auxcit].animate({opacity:0}, 1000, "", function(){
				texts2[currentIndext].animate({opacity:100}, 1000);	
			});
		};
		
		intervalt = setInterval(showt, showDurationt);

    }	
    
    if ($('#featmerc').length){
		var showDurationfm = 6000;
		var containerfm = $('#featmerc');
		var fm = containerfm.find('.featmerc_cont');
		var fm2 = new Array();
		var currentIndexfm =0;
		var intervalfm;
		
        var ifm=0;
		fm.each(function(){
			if(ifm > 0){
				$(this).hide();
			}
            ifm++;
            fm2[fm2.length] = $(this);
		});
		
		var showfm = function(){
			var auxcifm = currentIndexfm;
			currentIndexfm = currentIndexfm < fm2.length - 1 ? currentIndexfm+1 : 0;
			fm2[auxcifm].fadeOut(1000, function(){	
				fm2[currentIndexfm].fadeIn(1000);
				
			});
		};
		
		intervalfm = setInterval(showfm, showDurationfm);

    }    
	
	
});

