/**
 *
 * Plugin: Supa Flier 
 * Version: 2.0
 * Release: 12/6/2009 9:42:20 PM
 * Cms: e107.org
 * Update: 17/04/2010
 * Author: Luca Filosofi > aSeptik
 * Home: http://ask.altervista.org
 * Mail: aseptik@gmail.com     
 *
 */

addEvent(window, 'load', supaflier_init);

var sf_url = new function() {  

    var currentURL = window.location;
    
    var js_path = document.getElementById('supaflier_js').src;
    
    this.href = currentURL.href;
    // Displays 'http://www.example.com:80/example.cgi?x=3&y=4#results'
    this.protocol = currentURL.protocol;
    // Displays 'http:'
    this.host = currentURL.host;
    // Displays 'www.example.com:80'
    this.hostname = currentURL.hostname;
    // Displays 'www.example.com'
    this.port = currentURL.port;
    // Displays '80'
    this.pathname = currentURL.pathname;
    // Displays '/example.cgi'
    //this.search = currentURL.search;
    // Displays '?x=3&y=4'
    this.hash = currentURL.hash;
    // Displays '#results'
    // get the ajax path
    this.ajax = function() {
        var ajax_path = js_path.substring(0, js_path.lastIndexOf('/') - 2 ) ;
        return ajax_path ;
    };
    //get a url query string like php
    this.search = function () {
    var urlQuery = currentURL.search.split('?');
    if ( typeof (urlQuery) != 'undefined') { 
    return  urlQuery[1];
    } else {
    return null;
    }
    };
    
             
}; 

  var partner_id = jQuery('.gigya-partner-id').attr('id');
  var php_query = sf_url.search();
  var sf_ajax = sf_url.ajax() + 'ajax.php';
  var sf_path = sf_url.ajax();
  var swfu;

function supaflier_init() {

    if ( php_query != null ) {
          
    if ( php_query == 'add' ) {
        addImagesOnFlierPreview();
       
    }
    
    if ( php_query == 'edit' ) {
        switchThumbToListview();
        updateSfContent();
    }

    if ( php_query == 'chart' ) {
       // addSfComplexChart();
       // jQuery('select#sf_chart_select').selectmenu({style:'dropdown'});
    }
    
 	if ( php_query.indexOf('upload') != -1 ) {
    
        
    showAllImage();
    
    var upload_query = php_query.split("=");
    var session_id = upload_query[1];

	var settings = {
		flash_url : sf_path + "swfupload/swfupload.swf",
		upload_url: sf_path + "upload.php",
		post_params: { "PHPSESSID" : session_id },
		file_size_limit : "100 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,

		// Button Settings
		button_image_url : sf_path + "img/XPButtonUploadText_61x22.png",
		button_placeholder_id : "spanButtonPlaceholder1",
		button_width: 61,
		button_height: 22,

		// The event handler functions are defined in handlers.js
		swfupload_loaded_handler : swfUploadLoaded,
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : queueComplete,	// Queue plugin event
		
		// SWFObject settings
		minimum_flash_version : "9.0.28",
		swfupload_pre_load_handler : swfUploadPreLoad,
		swfupload_load_failed_handler : swfUploadLoadFailed
	};

	swfu = new SWFUpload(settings);
		
    }
       
if ( php_query.indexOf('banner') != -1 ) {

    var idlong = php_query.split("=");
    var id = idlong[1];
    
    if ( jQuery('#sf_alink_' + id).length > 0 ) {
        jQuery('html, body').animate({
            scrollTop: (jQuery('#sf_alink_' + id).offset().top - 80)
        },
        'slow',
        function() {
        
            jQuery.modal('<div style="width:400px;height:300px" id="divWildfirePost' + id + '"></div>');
            
       wildfireInitPost(id);
    
        });

    }
  }
}

// calendar js 
// MUST BE REMOVED IN NEXT VERSION

    jQuery("#addfield").click(function(){
    
        var ct = (jQuery("#divTxt").children("#txt").size() - 1) + 2;
        
        jQuery("#divTxt").append("<div id=\"txt\"><input type=\"text\" value=\"\" id=\"a-" + ct + "\" name=\"ne_thread[]\" style=\"width:280px;margin:5px 0;padding:5px;display:none\" class=\"tbox\" /> <a style=\"text-decoration:none\" id=\"" + ct + "\" onclick=\"jQuery(\'#" + ct + "," + "#a-" + ct + "\').fadeOut(\'slow\', function() { jQuery(this).remove(); });\" href=\"javascript:;\" title=\" Remove \"> <b>-</b> </a><div>");
        jQuery("#" + ct + "," + "#a-" + ct + "").css({
            "background-color": "yellow",
            "opacity": 0.5
        }).fadeIn("slow", function(){
            jQuery("#a-" + ct).css({
                "background-color": "#333333",
                "border": "1px solid #666666",
                "opacity": 1
            });
             jQuery("#" + ct).css({
                "background-color": "#000000",
                "border": "1px solid #000000",
                "opacity": 1
            });
        });
        
    });
// calendar js EOF

};



function img_delete(id) {

 //this.preventDefault(); 
 var parent = jQuery('#img_'+id).parent(); 
 var img =    jQuery('#img_'+id).prev().text();
 //alert(img);
 var query = 'action=delete_image&image=' + img;

    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        beforeSend: function() { 
        parent.animate({'backgroundColor':'#fb6c6c'},300); 
      }, 
        success: function(data) {
        parent.fadeOut(500).remove();
        },
        error: function() {
        //alert(query);
        }
    });

};

function showAllImage() {
jQuery('#show_all_images').find('*').fadeOut(500).remove();
 var query = 'action=show_all_images';
    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {
        jQuery('#show_all_images').append(data.responseText).fadeIn(500);
        },
        error: function() {
          //alert(query);
        }
    });
};


function preventEventClick( id ) {

 var query = 'action=click_count&sf_id=' + id;
    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {
        },
        error: function() {
          //alert(query);
        }
    });
};

function switchThumbToListview() {
jQuery("input.switch_thumb").toggle(function(){
        //showDisplay();  
       showListView();
    }, function () {
       // showListView();
       // updateSfContent();
       showDisplay();  
    }); 
    
    };

function showDisplay() {
jQuery("input.switch_thumb").removeClass('swap_display').addClass("swap_listview");
        jQuery("#fliers_images_container ul").fadeOut("fast", function() {
        jQuery(this).fadeIn("fast").addClass("display").removeClass("listview");
       });
};

function showListView() {
jQuery("input.switch_thumb").removeClass('swap_listview').addClass("swap_display");
        jQuery("#fliers_images_container ul").fadeOut("fast", function() {
        jQuery(this).fadeIn("fast").addClass("listview").removeClass("display");
        });
};  

function addImagesOnFlierPreview() {
   var sf_inputs = jQuery('#sf_top,#sf_src,#sf_down');
      
      sf_inputs.each(function() {
      var val = jQuery(this).val();
      var id = jQuery(this).attr('id');
        if ( val != '' ) {
            if ( id == 'sf_top' ) { 
                 jQuery('#sf_top_preview').append('<img class="' + id + '" src="' + val + '" alt="" />');
                 } else
                 if ( id == 'sf_src' ) { 
                 jQuery('#sf_mid_preview').append('<img class="' + id + '" src="thumb/flier_resized_' + val + '" alt="" />');
                 } else
                 if ( id == 'sf_down' ) { 
                 jQuery('#sf_down_preview').append('<img class="' + id + '" src="' + val + '" alt="" />');
                 }
            return;
        } else {
        
        }
    });

     
    /**
     * Flier Preview
     *      
     */ 
             
    jQuery('#sf_top,#sf_src,#sf_down').change(function() {

        var validExt = ['jpg', 'jpeg', 'gif', 'png'];
        var imgClass = jQuery(this).attr('id');
        var imgSrc = jQuery(this).val();
        //loop array
        for ( var i = 0; i < validExt.length; i++ ) {
             // check if url contain a valid img link 
            if ( imgSrc.toLowerCase().indexOf(validExt[i]) != -1 ) {
                
            // check if image already exists
            if ( jQuery('.' + imgClass ).attr('src') != imgSrc ) {
                
                // remove previous image
                jQuery('.' + imgClass ).remove();
                
                // add images in the right place
                 if ( imgClass == 'sf_top' ) { 
                 jQuery('#sf_top_preview').append('<img class="' + imgClass + '" src="' + imgSrc + '" alt="" />');
                 } else
                 if ( imgClass == 'sf_src' ) { 
                 jQuery('#sf_mid_preview').append('<img class="' + imgClass + '" src="thumb/flier_resized_' + imgSrc + '" alt="" />');
                 } else
                 if ( imgClass == 'sf_down' ) { 
                 jQuery('#sf_down_preview').append('<img class="' + imgClass + '" src="' + imgSrc + '" alt="" />');
                 }
                
                } 
            }
        }
    });
    
};

//});


function update_flier() {

    var sf_id = '#flier_' + jQuery('#sf_id').val();

    jQuery(sf_id).children('.flier_mid').remove().fadeOut(200);

    var query = 'action=update_flier&' + jQuery('#update_flier_form').serialize();

    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {


            jQuery(sf_id).append(data.responseText).fadeIn(200);
            updateSfContent();
            jQuery.modal.close();
        },
        error: function() {
            alert(query);
        }
    });


};

function insert_flier() {

    jQuery('#insert_responce_message').fadeOut(200);

    var query = 'action=insert_content&' + jQuery('#sf_add_form').serialize();

    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {
        jQuery( '#sf_add_form' )[0].reset();
            jQuery('#insert_responce_message').html(data.responseText).fadeIn(200);

        },
        error: function() {
           jQuery('#insert_responce_message').html(data.responseText).fadeIn(200);
        }
    });


};

function editThisFlier(id) {

    var query = 'action=edit_flier&sf_id=' + id;
    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {

            jQuery('#supaflier-modal-content').append(data.responseText);
        },
        error: function() {
            alert(query);
        }
    });

    jQuery('#supaflier-modal-content').modal();

};

function delThisFlier( id , mode ) {
    
    var sf_id = '#flier_' + id;
    
    var query = 'action=delete_flier&sf_id=' + id + '&sf_status=' + mode ;
    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {
        updateSfContent('listView');
        
            //jQuery(sf_id).children().remove().fadeOut(200);
            
        },
        error: function() {
            alert(query);
        }
    });

};

function updateSfContent(mode) {

if (sf_url.search() == 'edit') {
    jQuery('#fliers_images_container').find('*').remove().fadeOut(200);

    var query = 'action=update_content';
    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {

jQuery('#fliers_images_container').append(data.responseText).fadeIn(200);
        
jQuery("#sortable").sortable({
    handle: '.handle',
    update: function() {
        var order = jQuery('#sortable').sortable('serialize');
        var query = 'action=update_position&' + order;
        jQuery.ajax({
            url: sf_ajax,
            type: "POST",
            data: query

        });
    }
});
       if (mode == 'listView') {
       showListView();
       } else {
       showDisplay();  
       }
       
        },
        error: function() {
            alert(query);
        }
    });
  }

};

function showSfWildfire(id) {
jQuery.modal('<div style="width:400px;height:300px" id="divWildfirePost' + id + '"></div>');

wildfireInitPost(id); 

};

function confX(id) {
	this.id = id;
	this.gconf = function() {
	var conf = {
    onPostProfile: displayEventMessageX,
    CID: this.id,
    advancedTracking: 'true',
    defaultContent: 'sfcontent'+this.id,
    UIConfig: '<config><display showPost="true" showBookmark="true" showEmail="true" /></config>'
};	
    return conf;
	}
};
 
function wildfireInitPost(id) {

    pconf = new confX(id);

    Wildfire.initPost( partner_id , 'divWildfirePost'+id, 400, 300, pconf.gconf() );
    
};

function displayEventMessageX(eventObj) {
       
        var query = 'action=update_tracking&type='+eventObj.type+'&ModuleID='+eventObj.ModuleID+'&network='+eventObj.network+'&CID='+eventObj.CID+'&username='+eventObj.username;
        
    jQuery.ajax({
        type: 'POST',
        url: sf_ajax,
        data: query,
        complete: function(data) {
       
        },
        error: function() {
            alert(query);
        }
    });
};

//http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj["e"+type+fn] = fn;
    obj[type+fn] = function() { obj["e"+type+fn]( window.event ) };
    obj.attachEvent( "on"+type, obj[type+fn] );
  } 
  else{
    obj.addEventListener( type, fn, false );	
  }
}